调用Windows Shell并传递一些参数.NET c#

时间:2011-11-07 15:04:57

标签: c# .net windows shell

这是我的问题,我想用gpg.exe来解密一些数据。在此之前,我想测试并制作一个" ipconfig"通过Windows Shell。我试过了:

  

的Process.Start(" CMD"" IPCONFIG&#34);

没有成功。有人知道帮助我的方法吗?

感谢。

3 个答案:

答案 0 :(得分:5)

看看这个功能(取自here

   public static string ExecuteCmd(string arguments)
    {
        // Create the Process Info object with the overloaded constructor
        // This takes in two parameters, the program to start and the
        // command line arguments.
        // The arguments parm is prefixed with "@" to eliminate the need
        // to escape special characters (i.e. backslashes) in the
        // arguments string and has "/C" prior to the command to tell
        // the process to execute the command quickly without feedback.
        ProcessStartInfo _info =
            new ProcessStartInfo("cmd", @"/C " + arguments);

        // The following commands are needed to redirect the
        // standard output.  This means that it will be redirected
        // to the Process.StandardOutput StreamReader.
        _info.RedirectStandardOutput = true;

        // Set UseShellExecute to false.  This tells the process to run
        // as a child of the invoking program, instead of on its own.
        // This allows us to intercept and redirect the standard output.
        _info.UseShellExecute = false;

        // Set CreateNoWindow to true, to supress the creation of
        // a new window
        _info.CreateNoWindow = true;

        // Create a process, assign its ProcessStartInfo and start it
        Process _p = new Process();
        _p.StartInfo = _info;
        _p.Start();

        // Capture the results in a string
        string _processResults = _p.StandardOutput.ReadToEnd();

        // Close the process to release system resources
        _p.Close();

        // Return the output stream to the caller
        return _processResults;
    }

答案 1 :(得分:1)

  • 第一个参数是执行的文件,"cmd""C:\Windows\System32\cmd"的快捷方式。
  • 第二个参数是赋予程序的参数。在这里,你不能只写"ipconfig"。您必须使用/r/c/kcmd提供参数:
      

    / c或/ r:执行string指定的命令然后停止   / k:执行string指定的命令并继续。

  •   

Process.Start("cmd", "/r ipconfig");

答案 2 :(得分:1)

请注意声明

ProcessStartInfo("cmd", @"/C " + arguments);

与代码中的注释相反,@符号仅影响字符串"/C ",并且不会影响字符串arguments的内容。在这种情况下,它不会伤害任何东西,但也不会做任何事情。

与代码中的评论相反,\中的任何arguments确实需要转义。