【问题标题】:Using shell commands in C#在 C# 中使用 shell 命令
【发布时间】:2012-09-17 13:18:20
【问题描述】:

我在下面的代码中使用 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();

【问题讨论】:

  • 你在设置当前目录吗?如果不是,您的相对位置可能不是您认为的位置。
  • 位置/工作目录在这里很好。他们似乎不是问题

标签: c# process cmd


【解决方案1】:

您可以添加这些行 - 基于 RedirectStandardOutput

p.StartInfo.RedirectStandardOutput = true;
.....
p.Start();
string result = p.StandardOutput.ReadToEnd();

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

【讨论】:

  • 你应该在那里添加UseShellExecute = false
  • 谢谢。但奇怪的是,我没有观察到文件“monitor_Details.txt”的内容,这意味着该文件虽然已创建,但它是空的。 ">"写操作有什么问题吗?
  • 我很乐意帮助你 stack_pointer is EXTINCT,也许你的论点,有可能
  • 参数似乎是正确的 Aghilas,因为它们在 CmdPrompt 中也是如此。只是它们在 C# 中不起作用:(
【解决方案2】:

我遇到了完全相同的问题。一种解决方法是为进程提供用户名和密码参数以及“runas”动词。这将使新进程启动并能够读取/写入文件。我没有明确的解释,但它对我有用。

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

【讨论】:

    猜你喜欢
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 2012-09-17
    • 2014-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多