【问题标题】:cmd process won't execute correct commandcmd进程不会执行正确的命令
【发布时间】:2016-07-18 14:59:22
【问题描述】:

我正在开发一个项目,您可以在其中向 cmd.exe “发送”命令并接收输出。对于此命令,您需要一个文件路径 -k 和一个 url。 我有以下代码(名称和值已更改):

    string path = "C:\Users\program.exe"
    string pathcustom = "\"" + path + "\"";        //the path needs to be in quotation marks

    Process p = new Process();
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.UseShellExecute = false;

    string Address = "1.2.3"

    string command = pathcustom + " " + "-k" + " " + "https://username:passwort@serveradress" + Address;        //Serveradress is the URL

    p.StartInfo.Arguments = "/C " + command;
    p.StartInfo.RedirectStandardOutput = true;
    p.Start();

    string ReturnValue = p.StandardOutput.ReadToEnd();

此代码工作正常,就像我希望的那样,但我需要另一种完全相似的方法,只是地址看起来不同。在上面的代码中,它看起来像 1.2.3,但在下面的方法中,地址必须看起来像这样(包括反斜杠和引号) \"ab:cd:de\" 所以让我们假设这是

    string path = "C:\Users\program.exe"
    string pathcustom = "\"" + path + "\"";        

    Process p = new Process();
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.UseShellExecute = false;

    string Address = @"\""ab:cd:de\""";

    string command = pathcustom + " " + "-k" + " " + "https://username:passwort@serveradress" + Address;        

    p.StartInfo.Arguments = "/C " + command;
    p.StartInfo.RedirectStandardOutput = true;
    p.Start();

    string ReturnValue = p.StandardOutput.ReadToEnd();

当我重写代码以使 cmd 保持打开状态时,使用第一种方法可以获得我想要/期望的输出。但是使用第二种不工作的方法,它将命令发送到 cmd 并执行它,但它写为“消息”,该命令要么写错了要么找不到。但是,当我采用完全相同的代码时(通过streamwriter,我将cmd的命令写入文本文件)并将其复制到cmd中,它会像应有的那样执行它。所以基本上,如果我通过 c# 执行命令,它就是行不通的。请帮忙

【问题讨论】:

  • 如果您想要另一种仅在 Address 的值上有所不同的方法,请通过在方法输入中添加 Address 来使第一个更通用。
  • 第二个command 会有参数-khttps://username:passwort@serveradress\\\"ab:cd:de\\\"" 真的是有效的URL吗?
  • 我忘记在 -k 之后添加一个空格,但我的代码得到了它。地址在方法输入中,但是(为了简化)我为这个问题写了这样的地址

标签: c# http cmd


【解决方案1】:

您必须等待应用程序退出 使用类似 p.WaitForExit(milliseconds) 或检查 p.HasExited

【讨论】:

    【解决方案2】:

    根据this MSDN Post,为了让 StartInfo.Arguments 中的参数保留引号,您需要 "triple escape it" ,如下所示:

    string Address = "\\\"\"\"ab:cd:de\\\"\"\"; 
    string command = pathcustom + " " + "-k" + "https://username:passwort@serveradress" + Address;
    

    【讨论】:

    • 有两种方法。第一个是'"'在代码中你需要写\",'\'你需要\\第二个是在字符串的'"'前面添加一个@。例如:@"\"" " 将是 \"
    猜你喜欢
    • 2015-10-12
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多