【问题标题】:Executing netstat from C# app returns "File Not Found" error从 C# 应用程序执行 netstat 返回“找不到文件”错误
【发布时间】:2021-10-22 08:39:07
【问题描述】:

我正在尝试从我的 C# 代码执行 netstat 命令并得到“找不到文件”错误。 我必须指定“netstat.exe”在哪里吗?

如果是这样,如果(假设)netstat 和 findstr 位于两个不同的文件夹中,我该怎么做?

    Process cmd = new Process();
    cmd.StartInfo.FileName = "netstat -a | findstr 5840";
    cmd.StartInfo.RedirectStandardInput = true;
    cmd.StartInfo.RedirectStandardOutput = true;
    cmd.StartInfo.CreateNoWindow = true;
    cmd.StartInfo.UseShellExecute = false;

    try
    {
        cmd.Start();
    }
    catch (System.ComponentModel.Win32Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    cmd.StandardInput.Flush();
    cmd.StandardInput.Close();
    cmd.WaitForExit();
    StreamReader reader = cmd.StandardOutput;
    string output = reader.ReadToEnd();
    Console.WriteLine(output);

这就是解决问题的方法:

// create the ProcessStartInfo using "cmd" as the program to be run and "/c " as the parameters.
// /c tells cmd that we want it to execute the command that follows and then exit.
string command = "netstat -a | findstr " + sTCPPort;
ProcessStartInfo procStartInfo =  new ProcessStartInfo("cmd", "/c " + command);

// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
Process proc = new Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
result = proc.StandardOutput.ReadToEnd();

【问题讨论】:

    标签: c# command system.diagnostics


    【解决方案1】:

    如果没有看到确切的信息,很难知道确切的问题,但看起来您可能需要 cmd.exe 并将您的命令作为参数传递给它。

    【讨论】:

    • 是的,在看到您的回复之前,我按照您的建议做了同样的事情,并且奏效了。我已经用解决问题的更改更新了问题。我将您的回复标记为答案。
    猜你喜欢
    • 2015-06-15
    • 1970-01-01
    • 2017-03-16
    • 2014-02-12
    • 2017-02-04
    • 2020-11-03
    • 2021-04-06
    • 2019-07-03
    • 1970-01-01
    相关资源
    最近更新 更多