分享

C#模拟cmd

 _src_ 2023-02-06 发布于四川
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.IO; { class ShellCmd { /// <summary> /// Cmd命令运行工具 /// </summary> private string result; private string errinf; private Process process; private bool disposed; public ShellCmd() { disposed = false; } /// <summary> /// 是否忽略错误流(true可防卡死,但拿不到可能有的错误信息) /// </summary> public bool IngoreError { get; set; } /// <summary> /// 获取命令运行后的结果(包括全部命令行) /// </summary> public string Result { get { return result; } } /// <summary> /// 获取命令运行后的错误信息(如果有) /// </summary> public string Errinf { get { return errinf; } } /// <summary> /// 是否释放了 /// </summary> public bool Disposed { get { return disposed; } } /// <summary> /// 强制中止 /// </summary> public void Dispose() { if (process != null && !process.HasExited) { process.Kill(); process.Dispose(); disposed = true; } } /// <summary> /// 运行cmd命令 /// </summary> /// <param name="cmds">命令组</param> /// <param name="waitForExit">是否等待退出</param> /// <param name="needResult">是否需要获取输出结果</param> public void Run(string[] cmds, bool waitForExit=true, bool needResult=true) { result = errinf = string.Empty; ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.StandardOutputEncoding = Encoding.UTF8; startInfo.FileName = "cmd.exe"; startInfo.UseShellExecute = false; startInfo.RedirectStandardInput = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = IngoreError ? false : true; startInfo.CreateNoWindow = true; //startInfo.Verb = "runas"; startInfo.WindowStyle = ProcessWindowStyle.Hidden; process = Process.Start(startInfo); StreamWriter input = process.StandardInput; StreamReader output = process.StandardOutput; StreamReader error = null; if(!IngoreError) error = process.StandardError; foreach (string cmd in cmds) { input.WriteLine(cmd); input.Flush(); } input.Close(); if (needResult) result = output.ReadToEnd(); output.Close(); if (!IngoreError) { errinf = error.ReadToEnd(); error.Close(); } if(waitForExit) process.WaitForExit(); process.Close(); } } }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约