首页 > 解决方案 > C# OutputDataReceived 到标签只显示最后一行

问题描述

C# 新手,所以这可能有一个明显的答案,但现在我被卡住了。我正在尝试运行一个基本命令并将结果输出到标签或文本框。代码如下所示:

    protected void Button3_Click(object sender, EventArgs e)
    {
        ProcessStartInfo startInfo = new ProcessStartInfo("cmd", "/c " + "ping google.com")
        {
            WindowStyle = ProcessWindowStyle.Hidden,
            UseShellExecute = false,
            RedirectStandardOutput = true,
            CreateNoWindow = true
        };

        Process process = Process.Start(startInfo);
        process.OutputDataReceived += (s, a) => 
        {
            if (!String.IsNullOrEmpty(a.Data))
            {
                Response.Write(a.Data + "<br />");
                Label1.Text = a.Data + Environment.NewLine;
            }
        };
        process.BeginOutputReadLine();
        process.WaitForExit();
    }

Response.Write 输出按我的预期显示内容,但 Label1.Text 输出只显示最后一行。如何获取标签文本以显示命令的完整输出?任何帮助,将不胜感激。

标签: c#

解决方案


Label.Text = a.Data + Environment.NewLine;Label.Text每次都重新分配OutputDataRecieved被调用。如果你想追加它,解决方案是:

Label.Text += a.Data + Environment.NewLine;


推荐阅读