【问题标题】:Running cmd commands via .NET?通过 .NET 运行 cmd 命令?
【发布时间】:2010-10-16 01:22:39
【问题描述】:
System.Diagnostics.Process proc0 = new System.Diagnostics.Process();
proc0.StartInfo.FileName = "cmd";
proc0.StartInfo.WorkingDirectory = Path.Combine(curpath, "snd");
proc0.StartInfo.Arguments = omgwut;

现在介绍一些背景...

string curpath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);

omgwut 是这样的:

复制 /b a.wav + b.wav + ... + y.wav + z.wav output.wav

然后什么都没有发生。所以很明显出了点问题。我也尝试将“复制”作为可执行文件,但这不起作用。

【问题讨论】:

    标签: c# .net process cmd


    【解决方案1】:

    尝试使用 /C 为 cmd 的参数添加前缀,实际上是 cmd /C copy /b t.wav ...

    根据cmd.exe /?使用

    /C <command>

    执行指定的命令 字符串然后终止

    对于您的代码,它可能类似于

    // .. 
    proc0.StartInfo.Arguments = "/C " + omgwut;
    

    注意事项:

    • 测试您的命令是否有效的一个好方法是从命令提示符实际尝试它。如果您尝试执行cmd.exe copy ...,您会看到复制不会发生。
    • 可以作为参数传递的参数长度是有限制的。来自MSDN:“.NET Framework 应用程序中的最大字符串长度为2,003 个字符,.NET Compact Framework 应用程序中的最大字符串长度为488 个字符。”
    • 您可以通过使用System.IO 类打开文件并手动连接它们来绕过shelling out 命令。

    【讨论】:

      【解决方案2】:

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

      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
        }
      

      【讨论】:

      • 您应该在记录异常后添加throw;,除非此代码位于程序的顶层。这将允许异常传播给调用者。
      【解决方案3】:

      你也可以试试这个。。这样更好。

      System.Diagnostics.Process proc = new System.Diagnostics.Process(); 
      
      proc.EnableRaisingEvents=false;
      proc.StartInfo.FileName="iexplore";
      proc.StartInfo.Arguments="http://www.microsoft.com";
      
      proc.Start();
      
      proc.WaitForExit();
      
      MessageBox.Show("You have just visited " + proc.StartInfo.Arguments);
      

      【讨论】:

        【解决方案4】:

        Daniels cmd /c 想法会起作用。请记住,在您的情况下,命令行的长度可能有 8k 的限制,请参阅this 了解详细信息。

        因为无论如何您都在使用 .Net 应用程序,所以 File.Copy 可能比这种方法更容易/更干净。

        【讨论】:

        • 他正在尝试追加多个文件;不知道你是否可以用 File.Copy 做到这一点
        猜你喜欢
        • 2021-05-18
        • 2016-06-03
        • 1970-01-01
        • 2011-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多