src/DotNetCommon.Core/CmdHelper.cs

(完整代码) 1KB

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace DotNetCommon
{
    /// <summary>
    /// 运行CMD命令
    /// </summary>
    public static class CmdHelper
    {
        /// <summary>
        /// 运行cmd命令
        /// </summary>
        /// <param name="dir">运行目录</param>
        /// <param name="cmd">命令</param>
        public static string RunCmd(string cmd, string dir = null)
        {
            Process p = new Process();
            //设置要启动的应用程序
            p.StartInfo.FileName = "cmd.exe";
            //是否使用操作系统shell启动
            p.StartInfo.UseShellExecute = false;
            // 接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardInput = true;
            //输出信息
            p.StartInfo.RedirectStandardOutput = true;
            // 输出错误
            p.StartInfo.RedirectStandardError = true;
            //不显示程序窗口
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.WorkingDirectory = dir;
            //启动程序
            p.Start();

            p.StandardInput.AutoFlush = true;
            //向cmd窗口发送输入信息
            p.StandardInput.WriteLine(cmd);
            p.StandardInput.WriteLine("exit");

            //获取输出信息
            //等待程序执行完退出进程
            p.WaitForExit();
            string strOuput = p.StandardOutput.ReadToEnd();
            try
            {
                p.Close();
                p.Dispose();
            }
            catch { }
            return strOuput;
        }
    }
}

24 小时内免费解锁 3 个项目,之后 1 积分/个。 规则说明

AI 解读

登录后可用,每次 10 积分,解读结果公开显示在下面。

还没有人解读过这个文件。