[英]Execute a batch file in C#
我有一个批处理文件,它基本上从站点下载文件或返回错误消息,说文件不可用。 我想在C#(SSIS脚本组件)中执行此.bat文件并将文件名保存到变量(如果文件已下载)或将错误消息分配给变量。
先感谢您
使用Process.Start执行批处理文件。 您可以通过在返回的Process对象上读取StandardError和StandardOutput流来将过程输出作为文本获取。 您需要将RedirectStandardOutput
属性设置为true。
以下是MSDN的一个示例:
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "yourbatchfile.bat";
p.Start();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
您可以使用System.Diagnostics.Process运行带有/ C选项的Cmd.exe。 提供批处理文件的名称和您的基本信息。 为了简化包装过程创建和std输入和输出的捕获,我建议看一下我前面放在一起的ProcessRunner类。 如果不是至少阅读本文如何正确使用System.Diagnostics.Process 。
此外,您可能会在同一个库中查看ScriptRunner类,该类创建了一个围绕运行几种不同类型的Windows操作系统脚本文件的包装器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.