簡體   English   中英

異步讀取Stdout到字節數組

[英]Read Stdout asynchronously to byte array

我一直在嘗試使它與此處的多個教程/答案一起使用,但是不幸的是,它未能做到這一點。

我要執行的是執行一個過程,捕獲其DefaultOutput並將其添加到字節數組。 到目前為止,我得到的是:

private void startProcess(string path, string arguments)
{
    Process p = new Process();
    p.StartInfo.FileName = path;
    p.StartInfo.Arguments = arguments;
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.CreateNoWindow = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.RedirectStandardError = true;
    p.OutputDataReceived += p_OutputDataReceived;
    p.EnableRaisingEvents = true;
    p.Start();
    p.BeginErrorReadLine();
    p.BeginOutputReadLine();
    p.WaitForExit();
}

void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    string str = e.Data;
    // what goes here?!
}

我現在的問題是:如何將數據添加到(不斷增長的)字節數組中,或者是另一個更適合此目的的數據類型? 另外我不確定在哪里聲明此目標字節數組,最好將其放在startProcess方法中的某個位置,以便在進程退出后繼續處理數據,但是如何將其傳遞給p_OutputDataReceived

謝謝!

您可以嘗試一個內存流; 它確實可以滿足您的需求。

數組在C#中是不可變的,因此您不能擁有不斷增長的數組。 那就是List<T>目的。

如果您不關心字符編碼,請執行以下操作:

List<byte> OutputData = new List<byte>(); //global

void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    string str = e.Data;
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    OutputData.AddRange(bytes);
}

如果要使用顯式編碼:

void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    string str = e.Data;
    byte[] bytes = Encoding.ASCII.GetBytes(str); //or replace ASCII with your favorite
    //encoding
    OutputData.AddRange(bytes);
}

如果您確實想要完成后的字節數組,請執行以下操作:

byte[] OutputDataAry = OutputData.ToArray();

老實說,我認為List<string>是一種更干凈的方法,但是您需要一個byte[]所以我給您一個byte[]

如果您想一次讀取整個輸出,以下代碼將幫助您...

    static void Main(string[] args)
    {
        StreamReader reader;

        Process p = new Process();
        p.StartInfo.FileName = "cmd";
        p.StartInfo.Arguments = "/c echo hi";

        p.StartInfo.UseShellExecute = false;
        p.StartInfo.StandardOutputEncoding = Encoding.UTF8;
        p.StartInfo.RedirectStandardOutput = true;
        p.Start();
        reader = p.StandardOutput;

        byte[] result = Encoding.UTF8.GetBytes(reader.ReadToEnd());

        Console.WriteLine(result.ToString());
        Console.WriteLine(Encoding.UTF8.GetString(result));
        Console.ReadLine();
    }

如果不是這樣,您必須調用ReadToEnd以外的其他方法,並在線程中使用StreamReader來連續讀取數據...如果您想要增長的集合,則可以使用列表或類似的東西來代替字節數組...也請檢查與其他線程組合的同步集合http://msdn.microsoft.com/zh-cn/library/ms668265(v=vs.110).aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM