【问题标题】:Save The Cmd output into txt file in C#将 Cmd 输出保存到 C# 中的 txt 文件中
【发布时间】:2025-12-10 15:00:02
【问题描述】:

如何在 C# 中将 CMD 命令保存到 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();
    }

【问题讨论】:

    标签: c# cmd


    【解决方案1】:

    你可以重定向标准输出:

    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#

    【讨论】:

    • thanx alot ,但首先我想将结果保存到 txt 文件中,然后显示 1!!
    • @user3532929 看看我发布的第二个链接:*.com/questions/16256587/…