C# 执行指定命令和执行cmd命令

通常需要在程序执行过程中调用CMD命令并获取信息,以下方法实现了该功能。

/// 
/// 执行内部命令(cmd.exe 中的命令)
/// 
/// 命令行
/// 执行结果
public static string ExecuteInCmd(string cmdline)
{
    using (var process = new Process())
    {
        process.StartInfo.FileName = "cmd.exe";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.CreateNoWindow = true;

        process.Start();
        process.StandardInput.AutoFlush = true;
        process.StandardInput.WriteLine(cmdline + "&exit");

        //获取cmd窗口的输出信息  
        string output = process.StandardOutput.ReadToEnd();

        process.WaitForExit();
        process.Close();

        return output;
    }
}

以下方法实现了调用第三方实现的命令

/// 
/// 执行外部命令
/// 
/// 命令参数
/// 命令程序路径
/// 执行结果
public static string ExecuteOutCmd(string argument, string applocaltion)
{
    using (var process = new Process())
    {
        process.StartInfo.Arguments = argument;
        process.StartInfo.FileName = applocaltion;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.CreateNoWindow = true;

        process.Start();
        process.StandardInput.AutoFlush = true;
        process.StandardInput.WriteLine("exit");

        //获取cmd窗口的输出信息  
        string output = process.StandardOutput.ReadToEnd();

        process.WaitForExit();
        process.Close();

        return output;
    }
}
ProcessCore.ExecuteInCmd("ipconfig");
ProcessCore.ExecuteOutCmd("-I http://www.baidu.com", @"C:\curl.exe");



你可能感兴趣的:(代码日记(Dotnet))