通过.NET运行cmd命令?

unr*_*ity 4 .net c# cmd process

System.Diagnostics.Process proc0 = new System.Diagnostics.Process();
proc0.StartInfo.FileName = "cmd";
proc0.StartInfo.WorkingDirectory = Path.Combine(curpath, "snd");
proc0.StartInfo.Arguments = omgwut;
Run Code Online (Sandbox Code Playgroud)

现在有些背景......

string curpath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
Run Code Online (Sandbox Code Playgroud)

omgwut是这样的:

copy/b a.wav + b.wav + ... + y.wav + z.wav output.wav

一切都没有发生.显然有些不对劲.我也试过"复制"作为可执行文件,但这不起作用.

Dan*_*ant 16

/C有效地说,尝试使用cmd的参数作为前缀cmd /C copy /b t.wav ...

根据cmd.exe /?使用

/C <command>

执行string指定的命令然后终止

对于您的代码,它可能看起来像

// .. 
proc0.StartInfo.Arguments = "/C " + omgwut;
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 测试命令是否正常工作的一种好方法是从命令提示符中实际尝试它.如果你试图这样做,cmd.exe copy ...你会发现副本没有发生.
  • 您可以作为参数传递的参数的长度是有限制的.来自MSDN:"最大字符串长度是2,003.NET Framework应用程序中的488字符和.NET Compact Framework应用程序中的字符."
  • 您可以通过使用System.IO类打开文件并手动连接它们来绕过shelling out命令.


小智 5

试试这个它可能会帮助你..它与我的代码一起工作。

System.Diagnostics.ProcessStartInfo procStartInfo =
    new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
Console.WriteLine(result);
  }
  catch (Exception objException)
  {
  // Log the exception
  }
Run Code Online (Sandbox Code Playgroud)