【发布时间】: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 之后添加一个空格,但我的代码得到了它。地址在方法输入中,但是(为了简化)我为这个问题写了这样的地址