簡體   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