我正在尝试将进程响应作为字符串获取,以便在代码的不同位置使用它,这是目前我拥有的解决方案:
const string ex1 = @"C:\Projects\MyProgram.exe ";
const string ex2 = @"C:\Projects\ProgramXmlConfig.xml";
Process process = new Process();
process.StartInfo.WorkingDirectory = @"C:\Projects";
process.StartInfo.FileName = "MyProgram.exe ";
process.StartInfo.Arguments = ex2;
process.StartInfo.Password = new System.Security.SecureString();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
try
{
process.Start();
StreamReader reader = process.StandardOutput;
string output = reader.ReadToEnd();
}
catch (Exception exception)
{
AddComment(exception.ToString());
}
但是当我运行这个代码时,出现了以下错误:
"The system cannot find the file specified" error in process.Start(); without
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
这段代码运行正常,但只是打开了控制台窗口,所有进程的响应都被丢到那里,所以我无法将其用作字符串。
有人知道我为什么会出现这个错误,或者有不同的解决方案吗?
UseShellExecute
设置为false
会改变WorkingDirectory
的行为?我期望如果我设置了工作目录和文件名,它会使用工作目录来执行该文件。 - John GrabanskiUseShellExecute
的文档中可以了解到:“WorkingDirectory 属性的行为取决于 UseShellExecute 属性的值。当 UseShellExecute 为 true 时,WorkingDirectory 属性指定可执行文件的位置。如果 WorkingDirectory 是空字符串,则默认当前目录包含可执行文件。” - Jon Skeet