C#Process執行批處理後如何擷取傳回值?

來源:互聯網
上載者:User

標籤:

代碼如下   
p.StartInfo = new System.Diagnostics.ProcessStartInfo(path, pwd);
 p.Start();
其中path是個BAT的路徑!
我想要得到執行後的傳回值來判斷批處理運行期間是否錯誤?
請問如何做呢?
批次程式內容如下:
@echo off
for /f "delims=" %%a in (PCList.config) do net use \\%%a\ipc$ /delete
for /f "delims=" %%a in (PCList.config) do net use \\%%a\ipc$ %1 /user:administrator
pause

 

// Define the namespaces used by this sample.using System;using System.Text;using System.Globalization;using System.IO;using System.Diagnostics;using System.Threading;using System.ComponentModel;namespace ProcessAsyncStreamSamples{    class ProcessNetStreamRedirection    {        // Define static variables shared by class methods.        private static StreamWriter streamError =null;        private static String netErrorFile = "";        private static StringBuilder netOutput = null;        private static bool errorRedirect = false;        private static bool errorsWritten = false;        public static void RedirectNetCommandStreams()        {            String netArguments;            Process netProcess;            // Get the input computer name.            Console.WriteLine("Enter the computer name for the net view command:");            netArguments = Console.ReadLine().ToUpper(CultureInfo.InvariantCulture);            if (String.IsNullOrEmpty(netArguments))            {                // Default to the help command if there is not an input argument.                netArguments = "/?";            }            // Check if errors should be redirected to a file.            errorsWritten = false;            Console.WriteLine("Enter a fully qualified path to an error log file");            Console.WriteLine("  or just press Enter to write errors to console:");            netErrorFile = Console.ReadLine().ToUpper(CultureInfo.InvariantCulture);            if (!String.IsNullOrEmpty(netErrorFile))            {                errorRedirect = true;            }            // Note that at this point, netArguments and netErrorFile            // are set with user input.  If the user did not specify            // an error file, then errorRedirect is set to false.            // Initialize the process and its StartInfo properties.            netProcess = new Process();            netProcess.StartInfo.FileName = "Net.exe";            // Build the net command argument list.            netProcess.StartInfo.Arguments = String.Format("view {0}",                 netArguments);            // Set UseShellExecute to false for redirection.            netProcess.StartInfo.UseShellExecute = false;            // Redirect the standard output of the net command.              // This stream is read asynchronously using an event handler.            netProcess.StartInfo.RedirectStandardOutput = true;            netProcess.OutputDataReceived += new DataReceivedEventHandler(NetOutputDataHandler);            netOutput = new StringBuilder();            if (errorRedirect)            {                // Redirect the error output of the net command.                 netProcess.StartInfo.RedirectStandardError = true;                netProcess.ErrorDataReceived += new DataReceivedEventHandler(NetErrorDataHandler);            }            else             {                // Do not redirect the error output.                netProcess.StartInfo.RedirectStandardError = false;            }            Console.WriteLine("\nStarting process: net {0}",                 netProcess.StartInfo.Arguments);            if (errorRedirect)            {                Console.WriteLine("Errors will be written to the file {0}",                     netErrorFile);            }            // Start the process.            netProcess.Start();            // Start the asynchronous read of the standard output stream.            netProcess.BeginOutputReadLine();            if (errorRedirect)            {                // Start the asynchronous read of the standard                // error stream.                netProcess.BeginErrorReadLine();            }            // Let the net command run, collecting the output.            netProcess.WaitForExit();            if (streamError != null)            {                // Close the error file.                streamError.Close();            }            else             {                // Set errorsWritten to false if the stream is not                // open.   Either there are no errors, or the error                // file could not be opened.                errorsWritten = false;            }            if (netOutput.Length > 0)            {                // If the process wrote more than just                // white space, write the output to the console.                Console.WriteLine("\nPublic network shares from net view:\n{0}\n",                     netOutput);            }            if (errorsWritten)            {                // Signal that the error file had something                 // written to it.                String [] errorOutput = File.ReadAllLines(netErrorFile);                if (errorOutput.Length > 0)                {                    Console.WriteLine("\nThe following error output was appended to {0}.",                        netErrorFile);                    foreach (String errLine in errorOutput)                    {                        Console.WriteLine("  {0}", errLine);                    }                }                Console.WriteLine();            }            netProcess.Close();        }        private static void NetOutputDataHandler(object sendingProcess,             DataReceivedEventArgs outLine)        {            // Collect the net view command output.            if (!String.IsNullOrEmpty(outLine.Data))            {                // Add the text to the collected output.                netOutput.Append(Environment.NewLine + "  " + outLine.Data);            }        }        private static void NetErrorDataHandler(object sendingProcess,             DataReceivedEventArgs errLine)        {            // Write the error text to the file if there is something            // to write and an error file has been specified.            if (!String.IsNullOrEmpty(errLine.Data))            {                if (!errorsWritten)                {                    if (streamError == null)                    {                        // Open the file.                        try                         {                            streamError = new StreamWriter(netErrorFile, true);                        }                        catch (Exception e)                        {                            Console.WriteLine("Could not open error file!");                            Console.WriteLine(e.Message.ToString());                        }                    }                    if (streamError != null)                    {                        // Write a header to the file if this is the first                        // call to the error output handler.                        streamError.WriteLine();                        streamError.WriteLine(DateTime.Now.ToString());                        streamError.WriteLine("Net View error output:");                    }                    errorsWritten = true;                }                if (streamError != null)                {                    // Write redirected errors to the file.                    streamError.WriteLine(errLine.Data);                    streamError.Flush();                }            }        }    }} 
string arg = string.Format(backupFmt, server, user, pwd, database, file);  Process p = new Process();  p.StartInfo.FileName = "cmd.exe";  p.StartInfo.UseShellExecute = false;  p.StartInfo.WorkingDirectory = location + @"bin";  p.StartInfo.Arguments = arg;  p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;  p.StartInfo.CreateNoWindow = true;  p.StartInfo.RedirectStandardInput = true;  p.StartInfo.RedirectStandardOutput = true; p.Start();  StreamWriter sw = p.StandardInput;  sw.WriteLine(arg);  sw.WriteLine(Environment.NewLine);  sw.Close();#if DEBUG  StreamReader sr = p.StandardOutput;string str = sr.ReadToEnd();if(!string.IsNullOrEmpty(str)){Console.WriteLine("restore file:" + file);Console.WriteLine("message:" + str);}sr.Close();#endif  p.WaitForExit();  p.Close();

在C#中運行一個dos命令,並截取輸出、輸出資料流的問題,這個問題我以前在Java中實現過,由於在C#中沒有遇到過類似的 情況,為了避免每次別人問都要一遍一遍示範的情況,特地做了一個簡單的例子,實現在WinForm中ping一個網站,並且將ping的結果顯示在一個文字框中。

private void btnExecute_Click(object sender, EventArgs e)        {            tbResult.Text = "";            ProcessStartInfo start = new ProcessStartInfo("Ping.exe");//設定啟動並執行命令列檔案問ping.exe檔案,這個檔案系統會自己找到            //如果是其它exe檔案,則有可能需要指定詳細路徑,如運行winRar.exe            start.Arguments = txtCommand.Text;//設定命令參數            start.CreateNoWindow = true;//不顯示dos命令列視窗            start.RedirectStandardOutput = true;//            start.RedirectStandardInput = true;//            start.UseShellExecute = false;//是否指定作業系統外殼進程啟動程式            Process p=Process.Start(start);            StreamReader reader = p.StandardOutput;//截取輸出資料流            string line = reader.ReadLine();//每次讀取一行            while (!reader.EndOfStream)            {                tbResult.AppendText(line+" ");                line = reader.ReadLine();            }            p.WaitForExit();//等待程式執行完退出進程            p.Close();//關閉進程            reader.Close();//關閉流        }

 

C#Process執行批處理後如何擷取傳回值?

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.