将Cmd输出保存到C#中的txt文件中

时间:2014-11-02 21:10:17

标签: c# cmd

如何将CMD命令保存到C#

中的文本文件中

或如何在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();
    }

1 个答案:

答案 0 :(得分: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#