2017年8月16日 星期三

[WindowForm]如何由C#呼叫cmd並記錄執行的內容

[WindowForm]如何由C#呼叫cmd並記錄執行的內容


轉自

http://marcolue.pixnet.net/blog/post/6607000-%5Bwindowform%5D%E5%A6%82%E4%BD%95%E7%94%B1c%23%E5%91%BC%E5%8F%ABcmd%E4%B8%A6%E8%A8%98%E9%8C%84%E5%9F%B7%E8%A1%8C%E7%9A%84%E5%85%A7%E5%AE%B9

using System.Diagnostics;
using System.IO;
        public static string CommandOutput(string commandText)
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true; //不跳出cmd視窗
            string strOutput = null;
            try
            {
                p.Start();
                p.StandardInput.WriteLine(commandText);
                p.StandardInput.WriteLine("exit");
                strOutput = p.StandardOutput.ReadToEnd();//匯出整個執行過程                p.WaitForExit();
                p.Close();

            }
            catch (Exception e)
            {
                strOutput = e.Message;
            }
            return strOutput;
        }
 p.StandardInput 也可以配合StreamWriter做批次執行 例如:
                StreamWriter sw = p.StandardInput;
                sw.WriteLine("dir /w");
                sw.WriteLine(@"cd d:\test");
                sw.WriteLine(@"copy *.* c:\test");
                sw.Close(); 
或是匯出之txt檔案 例如:
        // 1: Write single line to new file
        using (StreamWriter sw = new StreamWriter("C:\\log.txt", true))
        {
            sw.WriteLine("Important data line 1");
        }
        // 2: Append line to the file
        using (StreamWriter sw = new StreamWriter("C:\\log.txt", true))
        {
            sw.WriteLine("Line 2");
        }
出來的結果會遞增至log.txt如下所示:
Important data line 1
Line 2 

沒有留言:

張貼留言