示例:找出某程序的PID
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Test3
{
class Program
{
static void Main(string[] args)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "netstat";
process.StartInfo.Arguments = "-a -n -o -p TCP";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
//process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
//process.StartInfo.CreateNoWindow = true;
process.Start();
string output = process.StandardOutput.ReadToEnd();
string[] lines = output.Split('\n');
process.WaitForExit();
Console.WriteLine(output);
foreach (string line in lines)
{
string[] tokens = Regex.Split(line, "\\s+");//按不可见字符分割
if (tokens.Length > 4)
{
int test = -1;
int.TryParse(tokens[5], out test);
if (test > 1023) //排除系统进程
{
try
{
var p = System.Diagnostics.Process.GetProcessById(test);
if (p.ProcessName == "Unity")
{
Console.WriteLine("Unity PID: {0}", test);
break;
}
}
catch
{
}
}
}
}
Console.ReadKey();
}
}
}
运行测试