2014-11-02 87 views
0

我怎麼能保存CMD命令成txt文件在C#保存在CMD輸出到C#txt文件

或者我如何能在C#中顯示命令提示符

這裏是我的代碼

     private void button1_Click(object sender, EventArgs e) 
    { 
     var p = new Process(); 

     string path = @"C:\Users\Microsoft"; 
     string argu = "-na>somefile.bat"; 
     ProcessStartInfo process = new ProcessStartInfo("netstat", argu); 
     process.RedirectStandardOutput = false; 
     process.UseShellExecute = false; 
     process.CreateNoWindow = false; 

     Process.Start(process); 

     p.StartInfo.WorkingDirectory = path; 
     p.StartInfo.FileName = "sr.txt"; 
     p.Start(); 
     p.WaitForExit(); 
    } 

回答

2

您可以重定向標準輸出:

using System; 
using System.Diagnostics; 
using System.IO; 

class Program 
{ 
    static void Main() 
    { 
    // 
    // Setup the process with the ProcessStartInfo class. 
    // 
    ProcessStartInfo start = new ProcessStartInfo(); 
    start.FileName = @"C:\7za.exe"; // Specify exe name. 
    start.UseShellExecute = false; 
    start.RedirectStandardOutput = true; 
    // 
    // Start the process. 
    // 
    using (Process process = Process.Start(start)) 
    { 
     // 
     // Read in all the text from the process with the StreamReader. 
     // 
     using (StreamReader reader = process.StandardOutput) 
     { 
     string result = reader.ReadToEnd(); 
     Console.Write(result); 
     } 
    } 
    } 
} 

代碼爲here

也期待這樣的回答:redirecting output to the text file c#

+0

感謝名單了很多,但首先我想要的結果保存成TXT文件的則顯示,1! – user3532929 2014-11-02 21:25:24

+0

@ user3532929比看看我貼的第二個鏈接:http://stackoverflow.com/questions/16256587/redirecting-output-to-the-text-file-c-sharp/16256623#16256623 – BendEg 2014-11-02 21:33:20