C#Process执⾏批处理后如何获取返回值?代码如下
p.StartInfo = new System.Diagnostics.ProcessStartInfo(path, pwd);
write的返回值p.Start();
其中path是个BAT的路径!
我想要得到执⾏后的返回值来判断批处理运⾏期间是否错误?
请问如何做呢?
批处理程序内容如下:
@echo off
for /f "delims=" %%a in (fig) do net use \\%%a\ipc$ /delete
for /f "delims=" %%a in (fig) 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 = "";
// 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 = "";
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#中运⾏⼀个命令,并截取输出、输出流的问题,这个问题我以前在Java中实现过,由于在C#中没有遇到过类似的情况,为了避免每次别⼈问都要⼀遍⼀遍演⽰的情况,特地做了⼀个简单的例⼦,实现在WinForm中ping⼀个⽹站,并且将ping的结果显⽰在⼀个⽂本框中。
private void btnExecute_Click(object sender, EventArgs e)
{
tbResult.Text = "";
ProcessStartInfo start = new ProcessStartInfo("");//设置运⾏的命令⾏⽂件问⽂件,这个⽂件系统会⾃⼰到
//如果是其它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();//关闭流
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论