How To: Execute command line in C#, get STD OUT results

后端 未结 17 1265
既然无缘
既然无缘 2020-11-21 13:12

How do I execute a command-line program from C# and get back the STD OUT results? Specifically, I want to execute DIFF on two files that are programmatically selected and wr

17条回答
  •  醉酒成梦
    2020-11-21 14:07

    This might be useful for someone if your attempting to query the local ARP cache on a PC/Server.

    List results = new List();
    
            using (Process p = new Process())
            {
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.Arguments = "/c arp -a";
                p.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
                p.Start();
    
                string line;
    
                while ((line = p.StandardOutput.ReadLine()) != null)
                {
                    if (line != "" && !line.Contains("Interface") && !line.Contains("Physical Address"))
                    {
                        var lineArr = line.Trim().Split(' ').Select(n => n).Where(n => !string.IsNullOrEmpty(n)).ToArray();
                        var arrResult = new string[]
                    {
                       lineArr[0],
                       lineArr[1],
                       lineArr[2]
                    };
                        results.Add(arrResult);
                    }
                }
    
                p.WaitForExit();
            }
    

提交回复
热议问题