如何在C#中shell执行文件?

我一如既往地尝试使用Process类,但是没有用。 我正在做的就是尝试运行Python文件,就像有人双击它一样。

可能吗?

编辑:

示例代码:

string pythonScript = @"C:\callme.py"; string workDir = System.IO.Path.GetDirectoryName ( pythonScript ); Process proc = new Process ( ); proc.StartInfo.WorkingDirectory = workDir; proc.StartInfo.UseShellExecute = true; proc.StartInfo.FileName = pythonScript; proc.StartInfo.Arguments = "1, 2, 3"; 

我没有收到任何错误,但脚本没有运行。 当我手动运行脚本时,我看到了结果。

这是我从C#执行python脚本的代码,带有重定向的标准输入和输出(我通过标准输入传递信息),从某个地方的Web上的示例复制。 Python位置是硬编码的,你可以看到,可以重构。

  private static string CallPython(string script, string pyArgs, string workingDirectory, string[] standardInput) { ProcessStartInfo startInfo; Process process; string ret = ""; try { startInfo = new ProcessStartInfo(@"c:\python25\python.exe"); startInfo.WorkingDirectory = workingDirectory; if (pyArgs.Length != 0) startInfo.Arguments = script + " " + pyArgs; else startInfo.Arguments = script; startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.RedirectStandardInput = true; process = new Process(); process.StartInfo = startInfo; process.Start(); // write to standard input foreach (string si in standardInput) { process.StandardInput.WriteLine(si); } string s; while ((s = process.StandardError.ReadLine()) != null) { ret += s; throw new System.Exception(ret); } while ((s = process.StandardOutput.ReadLine()) != null) { ret += s; } return ret; } catch (System.Exception ex) { string problem = ex.Message; return problem; } } 

Process.Start应该工作。 如果没有,你会发布你的代码和你得到的错误?

你忘了proc.Start()了。 如果你调用Start(),你的代码应该可以工作。