【问题标题】:C# starts some cmd commands but other doesn'tC# 启动一些 cmd 命令,但其他不启动
【发布时间】:2019-02-11 17:38:25
【问题描述】:

我的 windows 窗体应用程序触发了一个事件:

using System.Diagnostics;
string strCmdText = "'/C ping server1.example.com > C:\\Users\\myusername\\Desktop\\1\\a.txt";
Process.Start("cmd.exe", strCmdText);

执行时,cmd.exe 正在生成,运行一段时间,输出不显示,但它存在于重定向的 1.txt 文件中。


但是,我需要运行查询命令:

using System.Diagnostics;
string strCmdText = "'/C query user /server:server1.example.com > C:\\Users\\myusername\\Desktop\\1\\a.txt";
Process.Start("cmd.exe", strCmdText);

执行时,它会生成一个 cmd.exe,但仅持续 1 秒,然后消失,并且 1.txt 文件中不存在输出。


有什么方法可以在查询命令消失之前查看它的作用,例如在执行时保持打开状态?也许那里有一些有趣的东西。 或者,我做错了什么?也许我需要运行命令?

【问题讨论】:

  • 可以直接执行query而不是执行cmd来执行query
  • 如何将您的命令放入批处理文件并在文件末尾添加暂停?然后从 C# 执行批处理文件

标签: c# cmd command


【解决方案1】:

这边:

string outputProcess = "";
string errorProcess = "";

using (Process process = new Process())
{
    process.StartInfo.FileName = yourPath;
    process.StartInfo.Arguments = yourArguments;
    process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    process.Start();
    outputProcess = process.StandardOutput.ReadToEnd();
    errorProcess = process.StandardError.ReadToEnd();
    process.WaitForExit();
}

【讨论】:

  • 我编辑了 process.StartInfo.FileName = "C:\\Windows\\System32\\cmd.exe";和 process.StartInfo.Arguments = "查询用户 /server:ctx020-75it.group.pirelli.com";这会生成 cmd.exe,但它不会在输出中拍摄任何内容,也不会填充 1.txt。
【解决方案2】:

如果您真的想按照自己的方式运行代码。只需将“CMD”替换为“CMD /k”

【讨论】:

  • 我用 /k 替换了代码,现在它打开了 cmd.exe,它仍然存在,但找不到 query.exe 应用程序。奇怪的是,从生成的 CMD 中,我手动将目录更改为 C:/windows/system32/ 并且 query.exe 不存在。但是,如果我从我的计算机上打开 cmd,query.exe 存在……这真的很奇怪……如果我查看任务管理器,生成的 CMD 被命名为“Windows 命令处理器(32 位)”,并且如果我手动打开 cmd,在任务栏中命名为“Windows 命令处理器”
  • Process.Start(@"C:/windows/system32/cmd.exe", strCmdText)
  • 同样的事情,兄弟。没有任何变化。
猜你喜欢
  • 1970-01-01
  • 2012-10-07
  • 2019-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-11
  • 1970-01-01
相关资源
最近更新 更多