如何在读取另一个进程的重定向输出流时获得正确的编码

时间:2014-11-26 06:49:38

标签: c# character-encoding async-await

我正在启动另一个进程(node.exe)以捕获其输出并在我自己的Winforms窗口中显示它。我的想法是,如果节点服务器崩溃,我将能够自动重启进程。包含的代码只是测试代码,而不是最终代码,并且它不会终止进程,因此如果您运行它,您需要在关闭表单后手动终止 。 / p>

我的问题是虽然我正确地重定向了输出和错误流,但是有一些有趣的角色无法在普通控制台上显示。如何更改它以正确检测编码并正确显示?

这是一个输出样本(每个字符串开头有一些乱码)。

[32m[2014-11-26 08:24:21.525] [INFO] console - [39mExpress server listening on port 8080

这是启动流程的代码,并重定向输出:

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;

namespace AHVMonitor
{
    enum Output
    {
        StandardOutput,
        StandardError
    }

    public sealed class ProcessWatcher
    {
        private ConcurrentQueue<string> logLines = new ConcurrentQueue<string>();
        private Process process;
        private string arguments = ConfigurationManager.AppSettings["Arguments"];
        private string filename = ConfigurationManager.AppSettings["Filename"];

        public IList<string> Log
        {
            get { return logLines.ToArray(); }
        }

        public async Task<bool> WatchAsync()
        {
            Func<Task<bool>> waitForProcess = async () =>
            {
                var result = false;
                process = new Process();
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.FileName = filename;
                process.StartInfo.Arguments = arguments;
                process.StartInfo.WorkingDirectory = Path.GetDirectoryName(filename);

                // Hide the (empty) console window, since we are redirecting the output.
                process.StartInfo.CreateNoWindow = true;

                process.Start();

                await TaskExtensions.ForAsync(0, 3, 3, async i =>
                {
                    switch (i)
                    {
                        case 0:
                            await RedirectStandardErrorOrOutputAsync(Output.StandardOutput);
                            break;
                        case 1:
                            await RedirectStandardErrorOrOutputAsync(Output.StandardError);
                            break;
                        case 2:
                            result = await Task.Run(() =>
                            {
                                try
                                {
                                    process.WaitForExit();
                                    return process.ExitCode == 0;
                                }
                                catch { return false; }
                                finally
                                {
                                    process.Dispose();
                                    process = null;
                                }
                            });
                            break;
                    }
                });
                return result;
            };
            return await waitForProcess();
        }

        private async Task RedirectStandardErrorOrOutputAsync(Output outputType)
        {
            using (var reader = new StreamReader(outputType == Output.StandardError ? process.StandardError.BaseStream : process.StandardOutput.BaseStream))
            {
                var line = string.Empty;

                while ((line = await reader.ReadLineAsync()) != null)
                    logLines.Enqueue(line);
            }
        }
    }
}

要使该代码生效,您需要在3个任务上为 ForAsync 添加这两个扩展。 (包装不是我写的 ForEachAsync 实现。)

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AHVMonitor
{
    public static class TaskExtensions
    {
        #region IEnumerable<T>.ForEachAsync and IEnumerable<T>.ForAsync

        /// <summary>A ForEachAsync implementation. Based on a sample in an article by Stephen Toub,
        /// <a href="http://blogs.msdn.com/b/pfxteam/archive/2012/03/05/10278165.aspx">
        /// Implementing a simple ForEachAsync, part 2</a>.</summary>
        public static Task ForEachAsync<T>(this IEnumerable<T> source, int maxDegreeOfParallelism, Func<T, Task> body)
        {
            return Task.WhenAll(
                from partition in Partitioner.Create(source).GetPartitions(maxDegreeOfParallelism)
                select Task.Run(async () =>
                {
                    using (partition)
                        while (partition.MoveNext())
                            await body(partition.Current);
                }));
        }

        /// <summary>An asynchronous ForAsync implementation.</summary>
        /// <remarks>It simply creates an <b>Enumerable.Range</b> and wraps <b>ForEachAsync</b>.</remarks>
        public static Task ForAsync(int fromInclusive, int toExclusive, int maxDegreeOfParallelism, Func<int, Task> body)
        {
            return Enumerable.Range(
                fromInclusive, toExclusive).
                ForEachAsync(maxDegreeOfParallelism, async i => await body(i));
        }

        #endregion
    }
}

使用&#34; ProcessWatcher&#34;的表单代码,只包含一个按钮和一个文本框,是这样的:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AHVMonitor
{
    public partial class WatcherForm : Form
    {
        private ProcessWatcher watcher = new ProcessWatcher();

        public WatcherForm()
        {
            InitializeComponent();
        }

        private void WatcherForm_Load(object sender, EventArgs e)
        {
            LogAsync();
        }

        private async void LogAsync()
        {
            while (true)
            {
                await Task.Delay(TimeSpan.FromSeconds(1D));
                var lines = watcher.Log;
                logTextBox.Lines = lines.ToArray();
                logTextBox.SelectionStart = logTextBox.TextLength;
                logTextBox.ScrollToCaret();
            }
        }

        private async void startButton_Click(object sender, EventArgs e)
        {
            await watcher.WatchAsync();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

“垃圾”看起来像escape codes for setting colors,错过了不可打印的字符ESC(0x1B)。

相关问题