C# 执行CMD命令

作者: 吴杰 分类: 编程 发布时间: 2018-05-04 13:53

在.NET的项目开发中有时需要调用系统(Windows)命令,可以使用下面的函数来调用:

private static string InvokeCmd(string cmdArgs)
{
    string Tstr = "";
    Process p = new Process();
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardInput = true;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.RedirectStandardError = true;
    p.StartInfo.CreateNoWindow = true;
    p.Start();
    p.StandardInput.WriteLine(cmdArgs);
    p.StandardInput.WriteLine("exit");
    Tstr = p.StandardOutput.ReadToEnd();
    p.Close();
    return Tstr;
}

该函数经过项目测试,没有问题。