2010-06-02 18 views
0

我使用的本機窗口應用spamc.exe(SpamAssassin的 - sawin32)從命令行如下:如何在C#中傳遞文件名到StandardInput(Process)?

C:\ SpamAssassin的\ spamc.exe -R < C:\ email.eml

現在我想從C#調用這個過程:

Process p = new Process(); 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.RedirectStandardOutput = true; 
p.StartInfo.RedirectStandardInput = true; 
p.StartInfo.FileName = @"C:\SpamAssassin\spamc.exe"; 
p.StartInfo.Arguments = @"-R"; 
p.Start(); 

p.StandardInput.Write(@"C:\email.eml"); 
p.StandardInput.Close(); 
Console.Write(p.StandardOutput.ReadToEnd()); 
p.WaitForExit(); 
p.Close(); 

上面的代碼只傳遞文件名作爲字符串spamc.exe(不是文件的內容)。然而,這一個工程:

Process p = new Process(); 
p.StartInfo.UseShellExecute = false; 
p.StartInfo.RedirectStandardOutput = true; 
p.StartInfo.RedirectStandardInput = true; 
p.StartInfo.FileName = @"C:\SpamAssassin\spamc.exe"; 
p.StartInfo.Arguments = @"-R"; 
p.Start(); 

StreamReader sr = new StreamReader(@"C:\email.eml"); 
string msg = sr.ReadToEnd(); 
sr.Close(); 

p.StandardInput.Write(msg); 
p.StandardInput.Close(); 
Console.Write(p.StandardOutput.ReadToEnd()); 
p.WaitForExit(); 
p.Close(); 

有人能指出我爲什麼它的工作,如果我讀的文件,並傳遞給spamc的內容,但如果我只是通過文件名,因爲我想在做不起作用Windows命令行?

回答

4

這是因爲在命令行<有點神奇參數。它只是做了一點點,然後你可能會期待。實際上,它會打開文件並將其內容放入流程的標準輸入中。所以這與使用Process類時必須手動執行的操作相同。

正如您在第二個示例中已經顯示的那樣,您必須使用StreamReader來獲取文件的內容並將其放入StandardInput。只是爲了使它更強大一點,你可以使用這個小代碼片段:

using (var streamReader = new StreamReader(fileInfo.FullName)) 
{ 
    process.StandardInput.Write(streamReader.ReadToEnd()); 
    process.StandardInput.Flush(); 
} 
2

在第一個示例中,您傳遞的是表示文件的字符串不是文件

+0

好的,那麼傳遞文件的正確方法是什麼?除了第二個例子還有其他解決方案嗎? – Cosmo 2010-06-02 09:18:05

+0

除了改變程序打開文件本身,你的第二個解決方案是一個體面的方法。 – kenny 2010-06-02 09:29:22

1

你的第一代碼示例是從含有線C:\email.eml一個文件引導輸入的當量:

echo C:\email.eml > inputfile 
C:\SpamAssassin\spamc.exe -R < inputfile 

你的第二代碼樣品通過的C:\email.emlspamc的內容。

相關問題