【问题标题】:How to pass CMD argument with spaces?如何使用空格传递 CMD 参数?
【发布时间】:2017-05-02 11:35:52
【问题描述】:

我想运行简单的CMD 命令,而我的argument 包含空格(“”)。

在这种情况下,这不起作用,因为它被识别为带有多个 arguments 的命令...

这是我尝试过的(结果相同):

string arg = "c:\my path\ this is test\file.doc";

string.Format("\"{0}\"", arg)

编辑:

public void Invoke(string fileName, string arg)
{
    ProcessStartInfo processStartInfo = new ProcessStartInfo();
    processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    processStartInfo.FileName = fileName;
    if (arg != "")
        processStartInfo.Arguments = arg;
    processStartInfo.RedirectStandardOutput = true;
    processStartInfo.RedirectStandardError = true;
    processStartInfo.RedirectStandardInput = true;
    processStartInfo.UseShellExecute = false;
    processStartInfo.CreateNoWindow = true;

    Process process = new Process();
    process.StartInfo = processStartInfo;
    process.Exited += Process_Exited;
    process.EnableRaisingEvents = true;
    process.Start();
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();
}

用法:

string arg = "c:\my path\this is my string.ps1";   
Invoke(@"C:\windows\system32\windowspowershell\v1.0\powershell.exe", string.Format("\"{0}\"", arg)); 

【问题讨论】:

  • "不起作用,因为这被识别为带有多个参数的命令" 你的代码应该在哪里执行此操作?我没有看到你在哪里使用它......这是一个控制台应用程序:?请显示所有相关代码
  • 引用它是正确的方法。你如何阅读这些论点?见here。也仅供参考string arg = "c:\ this is test\file.doc"; 不编译,你想要string arg = @"c:\ this is test\file.doc";string arg = "c:\\ this is test\\file.doc";
  • 请看我的编辑

标签: c# cmd arguments


【解决方案1】:

在您的应用程序中,将所有参数连接在一起以获得一个空格分隔的参数,如下所示:

var joinedArgs = string.Join(" ", args);

然后将连接的参数传递给您的函数。

【讨论】:

    【解决方案2】:

    你可以试试这个:

    string arg = @"c:\\"my path\"\\"this is my string.ps1\"";   
    Invoke(@"C:\windows\system32\windowspowershell\v1.0\powershell.exe", 
    string.Format("\"{0}\"", arg));
    

    或 string arg = @"c:/\"我的路径\"/\"这是我的 string.ps1\"";

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-14
      • 2017-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多