无法将已执行命令的输出存储在文件 c# 控制台应用程序中

Unable to store output of executed commands inside a file c# console Application

我正在尝试将执行的命令结果存储在一个 txt 文件中,命令执行工作正常并且还显示命令提示符,但我无法将结果存储在我的文件中。

它只是在该文件夹中创建一个空文件。

Program.cs :

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace commandExecutionPractice
{
    class Program
    {
        static void Main(string[] args)
        {
            var folderPath = @"C:\";
            var fileName = @"\commandLog.txt";
            var fullPath = folderPath + fileName;
            StreamWriter writer = new StreamWriter(fullPath);

            using (CmdService cmdService = new CmdService("cmd.exe"))
            {
                string consoleCommand = String.Empty;
                do
                {
                    Console.WriteLine("Enter Command : ");
                    consoleCommand = Console.ReadLine();
                    string output = cmdService.ExecuteCommand(consoleCommand);
                    writer.WriteLine(">>> {0}", output);
                    Console.WriteLine(">>> {0}", output);
                }
                while (!String.IsNullOrEmpty(consoleCommand));
            }


            Console.ReadLine();
        }
    }
}

CmdService.cs :

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

namespace commandExecutionPractice
{
    public class CmdService : IDisposable
    {
        private Process _cmdProcess;
        private StreamWriter _streamWriter;
        private AutoResetEvent _outputWaitHandle;
        private string _cmdOutput;

        public CmdService(string cmdPath)
        {
            _cmdProcess = new Process();
            _outputWaitHandle = new AutoResetEvent(false);
            _cmdOutput = String.Empty;

            ProcessStartInfo processStartInfo = new ProcessStartInfo();
            processStartInfo.FileName = cmdPath;
            processStartInfo.UseShellExecute = false;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardInput = true;
            processStartInfo.CreateNoWindow = true;

            _cmdProcess.OutputDataReceived += _cmdProcess_OutputDataReceived;

            _cmdProcess.StartInfo = processStartInfo;
            _cmdProcess.Start();

            _streamWriter = _cmdProcess.StandardInput;
            _cmdProcess.BeginOutputReadLine();
        }

        public string ExecuteCommand(string command)
        {
            _cmdOutput = String.Empty;

            _streamWriter.WriteLine(command);
            _streamWriter.WriteLine("echo end");
            _outputWaitHandle.WaitOne();
            return _cmdOutput;
        }

        private void _cmdProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (e.Data == null || e.Data == "end")
                _outputWaitHandle.Set();
            else
                _cmdOutput += e.Data + Environment.NewLine;
        }

        public void Dispose()
        {
            _cmdProcess.Close();
            _cmdProcess.Dispose();
            _streamWriter.Close();
            _streamWriter.Dispose();
        }
    }
}

编辑:我添加了我忘记添加的 CmdService class 代码。

提前致谢。

这是一个简单的修复。

在您的 Main 函数中,在您按照以下方式写入流后添加行 writer.Flush();

writer.WriteLine(">>> {0}", output);
writer.Flush();

或者,如果您将流使用包装在 using 块中,它会在关闭流之前刷新它。

using (StreamWriter writer = new StreamWriter(fullPath))
{
    using (CmdService cmdService = new CmdService("cmd.exe"))
    {
        string consoleCommand = String.Empty;
        do
        {
            Console.WriteLine("Enter Command : ");
            consoleCommand = Console.ReadLine();
            string output = cmdService.ExecuteCommand(consoleCommand);
            writer.WriteLine(">>> {0}", output);
            Console.WriteLine(">>> {0}", output);
        }
        while (!String.IsNullOrEmpty(consoleCommand));
    }
}