C#遍历系统进程主要可以使用System.Diagnostics命名空间中的Process类实现。下面是具体步骤:
1.引入System.Diagnostics命名空间
using System.Diagnostics;
2.创建一个Process对象
Process process = new Process();
3.设置Process对象的属性
process.StartInfo.FileName = "tasklist.exe"; //设置进程名
process.StartInfo.Arguments = "/fo table"; //设置输出格式
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
4.启动Process进程并开始异步读取标准输出
process.Start();
process.BeginOutputReadLine();
5.监听Process对象的标准输出并输出每行字符串
process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
Console.WriteLine(e.Data);
}
});
下面是完整示例代码1:
using System;
using System.Diagnostics;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Process process = new Process();
process.StartInfo.FileName = "tasklist.exe";
process.StartInfo.Arguments = "/fo table";
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
Console.WriteLine(e.Data);
}
});
Console.ReadKey();
}
}
}
下面是完整示例代码2:
using System;
using System.Diagnostics;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Process[] processes = Process.GetProcesses();
foreach (Process process in processes)
{
Console.WriteLine("Process Name: {0}, Process ID: {1}", process.ProcessName, process.Id);
}
Console.ReadKey();
}
}
}
以上示例分别演示了使用Process类获取全部进程以及使用tasklist.exe获取进程信息的两种方法,可以根据自己的需求进行选择。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#遍历系统进程的方法 - Python技术站