2016-08-14 109 views
0

我試圖將命令窗口的輸出寫入文件,我可以正確地獲取輸出,並使用控制檯顯示它。但是,它似乎沒有登錄到我要寫入的文件?將控制檯的輸出寫入C#文件?

using (StreamWriter sw = new StreamWriter(CopyingLocation, true)) 
    { 
    Process cmd = new Process(); 

    cmd.StartInfo.FileName = "cmd.exe"; 
    cmd.StartInfo.RedirectStandardInput = true; 
    cmd.StartInfo.RedirectStandardOutput = true; 
    cmd.StartInfo.CreateNoWindow = false; 
    cmd.StartInfo.UseShellExecute = false; 

    cmd.Start(); 


    string strCmdText = "Some Command"; 
    string cmdtwo = "Some Other Command"; 


    cmd.StandardInput.WriteLine(cmdtwo); 
    cmd.StandardInput.WriteLine(strCmdText); 
    cmd.StandardInput.Flush(); 
    cmd.StandardInput.Close(); 

    //Writes Output of the command window to the console properly 
    Console.WriteLine(cmd.StandardOutput.ReadToEnd()); 

    //Doesn't write the output of the command window to a file 
    sw.WriteLine(cmd.StandardOutput.ReadToEnd()); 
    } 

回答

4

當您撥打ReadToEnd()時,它將讀取所有內容並且所有輸出都已消耗。你不能再次調用它。

您必須將輸出存儲在變量中並將其輸出到控制檯並寫入文件。

string result = cmd.StandardOutput.ReadToEnd(); 
Console.WriteLine(result); 
sw.WriteLine(result); 
+0

謝謝,它的工作!真棒! – chillax786