[英]Execute a batch file from c# and store result into a variable
我正在编写一个正在运行批处理文件的程序,该程序需要进一步的输出。 这是我的C#代码:
public void ExecuteBatFile()
{
Process proc = null;
try
{
string targetDir = string.Format("C:\\Users"); //this is where mybatch.bat lies
proc = new Process();
proc.StartInfo.WorkingDirectory = targetDir;
proc.StartInfo.FileName = "batch.bat";
proc.StartInfo.Arguments = string.Format("10"); //this is argument
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //this is for hiding the cmd window...so execution will happen in back ground.
proc.Start();
string output = proc.StandardOutput.ReadToEnd();
Console.WriteLine(output);
proc.WaitForExit();
}
catch (Exception ex)
{
Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
}
}
}
一旦运行,我会收到以下错误消息:
引发的异常:System.dll中的'System.InvalidOperationException'发生了:StandardOut尚未重定向或进程尚未开始。在CefSharp.MinimalExample.Wpf.CallBatchFile.ExecuteBatFile的System.Diagnostics.Process.get_StandardOutput()处。 ()在C:\\ Users \\ CefSharp.MinimalExamplemaster \\ CefSharp.MinimalExample.Wpf \\ CallBatchFile.cs:第27行
批处理文件成功运行,但是我无法将结果存储到变量中。 无论如何,我无法使它正常工作。 有没有人有任何建议? 这是我的一批猫:
@echo off
cd C:\users\934874
echo.>silvio.txt
title This is your first batch script!
echo Welcome to batch scripting!
if "%errorlevel%"=="0" cls &Echo Success.
if "%errorlevel%"=="1" cls &Echo Fail
pause
我期望的输出是控制台上的成功/失败,并将其作为字符串存储到变量中。 在此先感谢您的帮助
需要重定向输出
proc.StartInfo.RedirectStandardOutput = true;
如果UseShellExecute为false,则不使用WorkingDirectory属性查找可执行文件。 相反,它仅由已启动的进程使用,并且仅在新进程的上下文中才有意义。 如果UseShellExecute为false,则FileName属性可以是可执行文件的标准路径,也可以是系统将在PATH环境变量指定的文件夹中尝试找到的简单可执行文件名。
最简单的方法之一是使批处理文件将其输出写入文本文件。 然后,批处理完成后,您的主程序可以读取文本文件。
如果您真的想从标准输出流中读取内容,请查看以下其他SO文章: 从.NET应用程序(C#)捕获控制台输出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.