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 ...
随机推荐
- 【Android】读取sdcard卡上的全部图片而且显示,读取的过程有进度条显示
尽管以下的app还没有做到快图浏览.ES文件浏览器的水平,遇到大sdcard还是会存在读取过久.内存溢出等问题,可是基本思想是这种. 例如以下图.在sdcard卡上有4张图片, 打开app,则会吧sd ...
- 为了树莓派IIraspberrypi安装emacs+ecb+cedet+session+color-theme+cscope+linum
类似这篇文章写的不多,为了避免以后大家转来转去而忽略了写文章的时间,这些特别加上是2014年6月28日,省的对不上一些软件的版本号(下文中有些"最新"的说法就相应这个时间).假设转 ...
- Java 泛型具体解释
在Java SE1.5中.添加了一个新的特性:泛型(日本语中的总称型).何谓泛型呢?通俗的说.就是泛泛的指定对象所操作的类型.而不像常规方式一样使用某种固定的类型去指定. 泛型的本质就是将所操作的数据 ...
- POJ 1300 Door Man - from lanshui_Yang
Description You are a butler in a large mansion. This mansion has so many rooms that they are merely ...
- iOS发展 ---- 至iPhone 6自适应布局设计 Auto Layout
Apple从iOS 6增加了Auto Layout后開始就比較委婉的開始鼓舞.建议开发人员使用自适应布局,可是到眼下为止,我感觉大多数开发人员一直在回避这个问题,无论是不是因为历史原因造成的,至少他们 ...
- SOLOWHEEL - 电动独轮车 - SOLOWHEEL俱乐部聚会活动火热报名中
SOLOWHEEL - 电动独轮车 - SOLOWHEEL俱乐部聚会活动火热报名中 SOLOWHEEL俱乐部聚会活动火热报名中
- 深入了解java同步、锁紧机构
该薄膜还具有从本文试图一个高度来认识我们共同的同步(synchronized)和锁(lock)机制. 我们假定读者想了解更多的并发知识推荐一本书<java并发编程实战>,这是一个经典的书, ...
- sql语句查询数据库中的表名/列名/主键/自动增长值
原文地址:http://blog.csdn.net/pukuimin1226/article/details/7687538 ----查询数据库中用户创建的表 ----jsj01 为数据库名 sele ...
- Android之场景桌面(一)
声明:转载请务必注明出处,本文代码和主题仅供学习交流,请勿用于商业用途. 引言:最近Android场景桌面开始流行起来了,跟原始的Android桌面相比,场景桌面能逼真的模拟各种自然物体,并且通过点击 ...
- MySQL 全角转换为半角
序言: 用户注冊时候,录入了全角手机号码,所以导致短信系统依据手机字段发送短信失败.如今问题来了,怎样把全角手机号码变成半角手机号码? 1.手机号码全角转换成半角先查询出来全角半角都存在 ...