无法检测到bat文件是否正在运行。或者即使它被淹没了? [英] Unable to detect that the bat file is running or not. Or even if it is getting readed?

查看:96
本文介绍了无法检测到bat文件是否正在运行。或者即使它被淹没了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public partial class Service1 : ServiceBase
    {
        private Timer timer1 = null;

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timer1 = new Timer();
            this.timer1.Interval = 60000; //60 sec
            this.timer1.Elapsed +=new System.Timers.ElapsedEventHandler(this.timer1_Tick);
            timer1.Enabled=true;
            Library.WriteErrorLog("test windows service started");
            
        }

        private void timer1_Tick(object sender, ElapsedEventArgs e)
        {
            

            Process proc = null;
            try
            {
                string batrun = string.Format("cmd.exe","/c" + @"C:\Abhay\batfile");
                proc = new Process();
                proc.StartInfo.WorkingDirectory = batrun;
                proc.StartInfo.FileName = "webupknvp";
                proc.StartInfo.CreateNoWindow = false;
                proc.Start();
                proc.WaitForExit();
                
                
              

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace.ToString());
            }
            Library.WriteErrorLog("timer ticked and batch file executed");

        }

        protected override void OnStop()
        {
            timer1.Enabled = false;
            Library.WriteErrorLog("Test Service ended");
        }





我的尝试:



我们被困在这里仍在寻找可能的方式!!。



What I have tried:

We are stuck here still searching a possible way!!.

推荐答案

p.WaitForExit();

不要忘记检查其返回值以确保其实际成功:

Don't forget to check its return value to make sure it actually was successful:

if(p.ExitCode == 0) { // Or whatever return code you're expecting
    //...
}

如果您仍然遇到问题,请将代码移动到自己的函数并手动运行:

If you are still having problems, move the code to its own function and run manually:

private int RunProcess(string workDir, string appName, string args, bool hide = false)
{
	string batrun = string.Format("cmd.exe","/c" + @"C:\Abhay\batfile");
	proc = new Process();
	proc.StartInfo.WorkingDirectory = workDir;
	proc.StartInfo.FileName = appName;
	proc.StartInfo.Arguments = args
	proc.StartInfo.CreateNoWindow = hide;
	
	proc.Start();
	proc.WaitForExit();
	
	return p.ExitCode
}

然后从您的计时器事件中测试和使用变得非常简单:

Then testing and using from your timer event becomes very easy:

var result = RunProcess("c:\", "file.Bat", "", false);
if (result == 0)
{
	// success
}
else
{
	// failed ErrorLevel / app ExitCode
}


这篇关于无法检测到bat文件是否正在运行。或者即使它被淹没了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆