C#Process执行批处理后如何获取返回值?
代码如下
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执行批处理后如何获取返回值?的更多相关文章
- JAVA中执行JavaScript代码并获取返回值
JAVA中执行JavaScript代码并获取返回值 场景描述 实现思路 技术要点 代码实现 测试方法 运行结果 改进空间 场景描述 今天在CSDN上偶然看到一个帖子对于一段字符串 “var p=‘xx ...
- python 利用python的subprocess模块执行外部命令,获取返回值
有时执行dos命令需要保存返回值 需要导入库subprocess import subprocess p = subprocess.Popen('ping www.baidu.com', shell= ...
- python中subprocess.Popen执行命令并持续获取返回值
先举一个Android查询连接设备的命令来看看Python中subprocess.Popen怎么样的写法.用到的命令为 adb devices. import subprocess order='ad ...
- python执行系统命令后获取返回值
import os, subprocess # os.system('dir') #执行系统命令,没有获取返回值,windows下中文乱码 # result = os.popen('dir') #执行 ...
- python执行系统命令后获取返回值的几种方式集合
python执行系统命令后获取返回值的几种方式集合 今天小编就为大家分享一篇python执行系统命令后获取返回值的几种方式集合,具有很好的参考价值,希望对大家有所帮助.一起跟随小编过来看看吧 第一种情 ...
- Java--FutureTask原理与使用(FutureTask可以被Thread执行,可以被线程池submit方法执行,并且可以监控线程与获取返回值)
package com; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; i ...
- PCB MS SQL跨库执行SQL 获取返回值
一.SQL跨库执行SQL 获取返回值 ) DECLARE @sql nvarchar(MAX) DECLARE @layer INT SET @Dblink = 'P2.fp_db.dbo.' sel ...
- Yii2.0调用sql server存储过程并获取返回值
1.首先展示创建sql server存储过程的语句,创建一个简单的存储过程,测试用. SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE P ...
- execute sp_executesql 用变量获取返回值
execute sp_executesql 用变量获取返回值 1,EXEC的使用 2,sp_executesql的使用 MSSQL为我们提供了两种动态执行SQL语句的命令,分别是EXEC和sp_exe ...
随机推荐
- Centos 7 学习之静态IP设置
原文链接:http://blog.csdn.net/johnnycode/article/details/40624403 本学习主要针对 Centos 7.0.1406 版本进行学习整理! 如果你使 ...
- opencv MAT数据操作
1.存取单个像素值 最通常的方法就是 img.at<uchar>(i,j) = 255; img.at<Vec3b>(i,j)[0] = 255; 2.用指针扫描一幅图像 对于 ...
- 1.VMwareTools安装
1 选中虚拟机.右击.然后点击:安装Vmware-tool(最好是有网络的情况下安装) 2 将Vmware-tool的安装文件复制到暂时文件夹下,截图例如以下: 3 解压VMwareTools- ...
- HTML5系列之——applicationCache对象
ApplicationCache主要简单介绍: applicationCache对象实现HTML5相应WEB离线功能.以下我们来主要解说applicationCache对象的一些主要功能和方法 app ...
- 蜗牛—JSONJ学习ava转变
最近,写网站管理员,使用异步通信技术,所使用的方法是JSON数据传输模式 需要以下jar文件 然后,自己写了一点点经常使用代码 Java的List和数组要用JSONArray对象 Map和实体用JSO ...
- 基于Java的开源CMS系统选择(转)
CMS概述 对于网站CMS系统而言,基于PHP的是主流,如Drupal/Joomla在各个主流虚拟机提供商上都是标准配置,也被广泛使用. 但如果你拥有Java团队,或者项目目标是想建立一个企业网使用的 ...
- Remote Desktop Organizer – 管理组织远程桌面 - 小众软件
http://www.appinn.com/remote-desktop-organizer/
- AC自动机---个人总结
比较好的 AC自动机算法详解.. [转]http://www.cppblog.com/mythit/archive/2009/04/21/80633.html 个人总结:[图是盗用的..] ac自动机 ...
- Android - 缺少NDT选项和C/C++ Build选项 问题
缺少NDT选项和C/C++ Build选项 问题 本文地址: http://blog.csdn.net/caroline_wendy 时间: 2014.9.3 使用ADT(Android Develo ...
- 最牛B的编程套路
最近,我大量阅读了Steve Yegge的文章.其中有一篇叫“Practicing Programming”(练习编程),写成于2005年,读后令我惊讶不已: 与你所相信的恰恰相反,单纯地每天埋头于工 ...