using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
namespace Mesnac.Basic
{
///
/// windows命令辅助类
///
public class WinCmdHelper
{
#region 执行Dos命令
///
/// 执行Dos命令
///
/// Dos命令及参数
/// 是否显示cmd窗口
/// 执行完毕后是否关闭cmd进程
/// 成功返回true,失败返回false
public static bool ExcuteDosCommand(string cmd, bool isShowCmdWindow, bool isCloseCmdProcess)
{
try
{
Process p = new Process();
p.StartInfo.FileName = "cmd";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
//p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = !isShowCmdWindow;
p.OutputDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs e) {
if (!String.IsNullOrEmpty(e.Data))
{
ICSharpCode.Core.LoggingService.Debug(e.Data);
}
});
p.Start();
StreamWriter cmdWriter = p.StandardInput;
p.BeginOutputReadLine();
if (!String.IsNullOrEmpty(cmd))
{
cmdWriter.WriteLine(cmd);
}
cmdWriter.Close();
p.WaitForExit();
if (isCloseCmdProcess)
{
p.Close();
}
ICSharpCode.Core.LoggingService.Info(String.Format("成功执行Dos命令[{0}]!", cmd));
return true;
}
catch (Exception ex)
{
ICSharpCode.Core.LoggingService.Error("执行命令失败,请检查输入的命令是否正确:" + ex.Message, ex);
return false;
}
}
#endregion
#region 判断指定的进程是否在运行中
///
/// 判断指定的进程是否在运行中
///
/// 要判断的进程名称,不包括扩展名exe
/// 进程文件的完整路径
/// 存在返回true,否则返回false
public static bool CheckProcessExists(string processName, string processFileName)
{
Process[] processes = Process.GetProcessesByName(processName);
foreach (Process p in processes)
{
if (!String.IsNullOrEmpty(processFileName))
{
if (processFileName == p.MainModule.FileName)
{
return true;
}
}
else
{
return true;
}
}
return false;
}
#endregion
#region 结束指定的windows进程
///
/// 结束指定的windows进程,如果进程存在
///
/// 进程名称,不包含扩展名
/// 进程文件完整路径,如果为空则删除所有进程名为processName参数值的进程
public static bool KillProcessExists(string processName, string processFileName)
{
try
{
Process[] processes = Process.GetProcessesByName(processName);
foreach (Process p in processes)
{
if (!String.IsNullOrEmpty(processFileName))
{
if (processFileName == p.MainModule.FileName)
{
p.Kill();
p.Close();
}
}
else
{
p.Kill();
p.Close();
}
}
ICSharpCode.Core.LoggingService.Info(String.Format("成功结束[{0}]进程!", processes));
return true;
}
catch(Exception ex)
{
ICSharpCode.Core.LoggingService.Error("结束指定的Widnows进程异常:" + ex.Message, ex);
return false;
}
}
#endregion
}
}