簡體   English   中英

在C#中執行批處理文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM