[英]To check MyBat.bat file is running or not in C#
How can I check through C# code, if MyBat.bat file is running or not in the system. 如果系统中没有运行MyBat.bat文件,如何检查C#代码。
I have tried this but not working properly.Please suggest some other way. 我已经尝试过,但是无法正常工作。请提出其他建议。
Process proc = new Process();
proc.StartInfo.FileName = @"D:\MyBat.bat";
if (proc.Start())
{
Console.Write("This is bat files Open!.");
}
else
{
Console.Write("Welcome");
}
I only want to check MyBat.bat file is running in the system or not. 我只想检查MyBat.bat文件是否在系统中运行。 Because .bat file run in Command Prompt so how can i verify that MyBat.bat file is running. 由于.bat文件在命令提示符中运行,因此我如何验证MyBat.bat文件正在运行。
You should invoke your batch file via cmd.exe /c
, not directly. 您应该通过cmd.exe /c
而不是直接调用批处理文件。
so: 所以:
var command = "foo.bat";
Process p = new Process(){
StartInfo = new ProcessStartInfo("cmd.exe", "/c " + command)
};
var started = p.Start();
if(started)
{
Console.WriteLine("started");
var sync = true; //or false, see below
if(sync)
{
//either wait synchronously
p.WaitForExit();
Console.WriteLine("finished");
}
else
{
//or wait for an exit event asynchronously
p.Exited += (a, b) => { Console.WriteLine("finished"); }
}
}
else
{
Console.WriteLine("not started");
}
If you want to know right now, you can check the HasExited property. 如果您现在想知道,可以检查HasExited属性。
var isRunning = !myProcess.HasExited; var isRunning =!myProcess.HasExited;
If it's a quick process, just wait for it. 如果这是一个快速的过程,请等待。
myProcess.WaitForExit(); myProcess.WaitForExit();
If you're starting one up in the background, subscribe to the Exited event after setting EnableRaisingEvents to true. 如果您要在后台启动,请在将EnableRaisingEvents设置为true之后订阅Exited事件。
myProcess.EnableRaisingEvents = true; myProcess.EnableRaisingEvents = true;
myProcess.Exited += (sender, e) => { MessageBox.Show("Process exited"); myProcess.Exited + =(发送方,e)=> {MessageBox.Show(“流程已退出”); }; };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.