异步执⾏Dos命令
1//Minute
2 const int _defaultTimeOut =24*60;
3
4///<summary>
5///执⾏命令⾏
6///</summary>
7///<param name="cmdLine">程序集名称(或批处理⽂件)</param>
8///<param name="args">参数</param>
9///<param name="outputsAction">处理命令⾏的输出流信息</param>
10///<param name="errorsAction">处理命令⾏的错误输出信息</param>
11///<param name="timeOut">超时时间(单位:分钟)</param>
12public static void ExecuteCommandeLine(String cmdLine, String args, Action<object, DataReceivedEventArgs> outputsAction, Action<object, DataReceivedEventArgs> errorsAction, int timeOut = _defaultTimeOut)
13 {
14 Process process = new Process();
15 process.StartInfo.RedirectStandardError = true;
16 process.StartInfo.RedirectStandardOutput = true;
17 process.StartInfo.RedirectStandardInput = true;
18 process.StartInfo.CreateNoWindow = true;
19 process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
20 process.StartInfo.UseShellExecute = false;
21 process.StartInfo.LoadUserProfile = true;
22 process.StartInfo.StandardOutputEncoding = Encoding.UTF8;
23
24if (cmdLine.ToLower().Contains(".bat"))
25 {
26 process.StartInfo.FileName = "";
27 process.StartInfo.Arguments = "/c" + " " + cmdLine + " " + args;
28 }
29else
30 {
31 process.StartInfo.FileName = cmdLine;
32 process.StartInfo.Arguments = args;
33 }
34if (outputsAction !=null)
35 process.OutputDataReceived += new DataReceivedEventHandler(outputsAction);
36if (errorsAction !=null)
37 process.ErrorDataReceived += new DataReceivedEventHandler(errorsAction);
38
39 process.Start();
40 process.BeginOutputReadLine();
41 process.BeginErrorReadLine();
42
43int i =0;
44while (!process.HasExited)
45 {
46if (i++> timeOut *60&& !process.HasExited)
47 {
48 process.Kill();
49 process.Close();
50 throw new Exception(string.Format("Command line dLine:{0},args:{1}", cmdLine, args));
51 }
52 Thread.Sleep(1000);
53 }
54 }
55
56
57///<summary>
58///执⾏命令⾏
59///</summary>
60///<param name="cmdLine">程序集名称(或批处理⽂件)</param>
61///<param name="args">参数</param>
62///<param name="outputs">命令⾏输出信息</param>
63///<param name="errors">命令⾏输出错误信息</param>
64///<param name="timeOut">超时时间(单位:分钟)</param>
65public static void ExecuteCommandeLine(String cmdLine, String args, out string outputs, out string errors, int timeOut = _defaultTimeOut)
66 {
67 StringBuilder outputString = new StringBuilder();
68 StringBuilder errorString = new StringBuilder();
69 outputs = string.Empty;
70 errors = string.Empty;
71
72 ExecuteCommandeLine(cmdLine, args,
73 (o, d) =>
74 {
75if (d.Data !=null&& outputString.MaxCapacity > outputString.Length + d.Data.Length +10)
param name76 outputString.AppendLine(d.Data);
77 },
78 (o, d) =>
79 {
80if (d.Data !=null&& errorString.MaxCapacity > errorString.Length + d.Data.Length +10)
81 errorString.AppendLine(d.Data);
82 },
83 timeOut);
84 outputs = outputString.ToString();
85 errors = errorString.ToString();
86 }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论