在C#中使用shell命令

时间:2012-09-17 13:18:20

标签: c# process cmd

我在下面的代码中使用DevCon.exe捕获内容并将其写入文件中。我解析这个文件是为了需要。

Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C devcon.exe find = port *monitor* > monitor_Details.txt";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = true;
p.StartInfo.Verb = "runas";
p.Start();

不幸的是,使用此代码,我没有看到任何文本文件创建。所以,虽然我提到过,但这里没有考虑shell命令。 相同的命令在CMDLine中有效。

任何人都可以帮助解决出错的问题吗?

我也尝试使用下面的代码,但它不起作用。

Process p = new Process();
p.StartInfo.FileName = "devcon.exe";
p.StartInfo.Arguments = "find = port *monitor* > monitor_Details.txt";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = true;
p.StartInfo.Verb = "runas";
p.Start();

2 个答案:

答案 0 :(得分:3)

您可以根据RedirectStandardOutput

添加这些行
p.StartInfo.RedirectStandardOutput = true;
.....
p.Start();
string result = p.StandardOutput.ReadToEnd();

链接:http://msdn.microsoft.com/fr-fr/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx

答案 1 :(得分:0)

我遇到了完全相同的问题。解决方法是为进程提供UserName和Password参数以及“runas”动词。这将使新进程开始提升并能够读/写文件。我没有明确的解释,但它对我有用。

p.StartInfo.Verb = "runas";
p.StartInfo.UserName = Environment.UserName;
p.StartInfo.Password = PromptUserPassword(); //Get password as SecureString 
相关问题