【问题标题】:C# only show one specific line from CMDC# 只显示 CMD 中的一个特定行
【发布时间】:2020-04-08 13:45:28
【问题描述】:

我想如果 cmd 只完成标签中显示的第 10 行,但我不知道它是否可能或否如果是怎么办?也许有数组?这个程序应该在用户密码过期时得到。

private void AccountBtn_Click(object sender, EventArgs e)
{
        Process pw = new Process();
        pw.StartInfo.UseShellExecute = false;
        pw.StartInfo.RedirectStandardOutput = true;
        pw.StartInfo.FileName = "cmd.exe";
        pw.StartInfo.Arguments = "/c net user " + System.Environment.UserName + " /domain";
        pw.Start();
        label1.Text = pw.StandardOutput.ReadToEnd();
        pw.WaitForExit();
}

【问题讨论】:

    标签: c# arrays cmd process line


    【解决方案1】:

    您可以执行以下操作:

    var counter = 0;
    while (!p.StandardOutput.EndOfStream)
    {
        var line = p.StandardOutput.ReadLine();
        counter++;
    
        if (counter == 10)
        {
                label1.Text = line;
                break;
        }
    }
    

    或者你也可以这样做(不值得):

    label1.Text = p.StandardOutput
                   .ReadToEnd()
                   .Split(new[] { Environment.NewLine },
                          StringSplitOptions.None)
                   .Skip(9);
    

    【讨论】:

    • 我尝试了第一个,但没有任何反应。这是现在的样子:pw.Start(); pw.StandardOutput.ReadToEnd(); var counter = 0; while (!pw.StandardOutput.EndOfStream) { var line = pw.StandardOutput.ReadLine(); counter++; if (counter == 10) { label1.Text = line; break; } } pw.WaitForExit(); }
    • @Tamás 当您调用ReadToEnd 时,该进程可能甚至还没有开始写入输出流。一旦进程完成或空闲,您可能想致电ReadToEnd
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2012-04-28
    • 1970-01-01
    相关资源
    最近更新 更多