2015-04-16 37 views
1

我一直在試圖弄清楚爲什麼我不能使用>>(append)作爲我的p.StartInfo.Argument的一部分。當我刪除「>」它完美的作品,但當我嘗試使用「>」或「>>」我得到一個「不正確的參數」錯誤。我已經提前完成了,沒有>或>>編寫我的程序,只是將輸出存儲到一個字符串中,並稍後將其寫入文件。有人可以解釋爲什麼「>」或「>>」在這種情況下不起作用嗎?C#將過程結果重定向到文本文件

// Start the child process. 
Process p = new Process(); 
// Redirect the output stream of the child process. 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.RedirectStandardOutput = true; 
p.StartInfo.FileName = "attrib.exe"; 
startInfo.Arguments = "/S *.jpg > mypics.txt"; 

p.Start(); 

回答

0

輸出重定向運算符>cmd.exe的一個功能,不是操作系統。使用它用簡單的方式是因此調用cmd像這樣:

p.StartInfo.FileName = "cmd.exe"; 
startInfo.Arguments = "/C \"attrib.exe /S *.jpg > mypics.txt\""; 

重定向輸出正確的方法,但是,是先設置StartInfo.RedirectStandardOutputtrue(你所做的那樣),然後通過管道從輸出Process.StandardOutput的文件,像這樣:

using(StreamWriter file = new StreamWriter("mypics.txt")) { 
    p.StandardOutput.CopyTo(file); 
} 

或者異步版本:

using(StreamWriter file = new StreamWriter("mypics.txt")) { 
    await p.StandardOutput.CopyToAsync(file); 
} 
+0

我還沒有機會嘗試我們的建議,但我很想看看雙引號是否會讓我脫離使用重定向操作符。 – snapplex

+0

這不是雙引號,因爲它是對「cmd.exe」的調用。我實際上推薦使用後者的版本(使用'StandardOutput.CopyTo'),它可以消除對「cmd.exe」的依賴。 – SlugFiller

0

這是因爲>>>是不是attrib.exe解釋變量,他們要cmd.exe指令。

你可以嘗試,而不是像:

p.StartInfo.FileName = "cmd.exe"; 
p.StartInfo.Arguments = "/c attrib.exe /S *.jpg > mypics.txt"; 

此外,這是一個紅鯡魚:

p.StartInfo.RedirectStandardOutput = true; 

如果你想讀的C#代碼的輸出和寫入文件自己,你'd使用這個選項。這對於使用>輸出重定向器沒有幫助。

+0

我想使用重定向操作符,但C#迫使我的漢d並且我不想創建批處理文件。 – snapplex

相關問題