繁体   English   中英

批处理文件未从C#代码运行

[英]Batch file not running from c# code

我在共享位置有一个批处理文件,该批处理文件是我从.net代码执行的,但实际上该批处理文件未执行,这是因为批处理文件的整个代码都无法正常工作,而部分代码却在工作。 我假设.net代码执行正在完成并停止批处理文件的执行。 下面是我的.net代码

private static void ExecuteCommand(string command, string arguments)
    {
        try
        {
            Console.WriteLine("Code execution starts");
            Console.WriteLine("command: " + command);
            Console.WriteLine("arguments: " + arguments); 
            var process = new Process();

            process.StartInfo.FileName = command;
            if (!string.IsNullOrEmpty(arguments))
            {
                process.StartInfo.Arguments = arguments;
            }

            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            //process.StartInfo.CreateNoWindow = false;
            //process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
            process.StartInfo.UseShellExecute = true;
            process.EnableRaisingEvents = true;
            //process.StartInfo.RedirectStandardError = true;
            //process.StartInfo.RedirectStandardOutput = true;
            string stdError;
           // process.Start();
            Thread.Sleep(60000);
            ThreadPool.QueueUserWorkItem(delegate
            {
                process.Start();
               // process.WaitForExit();
            });
            //Thread.Sleep(60000);

            //ThreadStart ths = new ThreadStart(delegate()
            //{
            //    process.Start();
            //    //process.BeginOutputReadLine();
            //    //stdError = process.StandardError.ReadToEnd();
            //});

           //process.Start();

           //process.BeginOutputReadLine();
           //stdError = process.StandardError.ReadToEnd();

            Console.WriteLine("Code execution ends");
        }
        catch (Exception e)
        {
            Console.WriteLine("Code execution error: "+e.Message +"||"+e.InnerException.ToString()); 

        }
    }

要求是开始执行批处理文件,并且不要等待批处理文件执行的任何输出或完成。 当我从命令提示符或Windows资源管理器中运行批处理文件时,它工作正常。 无法在.net代码中使用cmd.exe,因为当批处理文件不存在或权限问题时,我们需要处理例外情况

我认为您可以使用WaitForExit方法,而不使用可能不够的Sleep。

有关它的更多信息: http : //msdn.microsoft.com/zh-cn/library/ty0d8k56.aspx

如果这不起作用,则可以使用一种解决方法,例如使用在过程开始之前创建的文件,并在批处理结束时将其删除,然后由FileSystemWatcher定期检查该文件( http://msdn.microsoft.com /en-us/library/system.io.filesystemwatcher(v=vs.110).aspx ),以检查该过程是否完成。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM