c# 进程判断

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace ProcessMonitoring
{
class ProcessMonitoring
{
public bool CheckForIllegalCrossThreadCalls { get; private set; }
string logPath = System.Environment.CurrentDirectory + @"\log.txt";
string date = System.DateTime.Now.ToString() + ":";
/// <summary>
/// 根据运行路径截取进程名
/// </summary>
/// <param name="pathName"></param>
/// <returns></returns>
public string getProcessName(string pathName)
{
string processName = "";
try
{
processName = pathName.Substring(pathName.LastIndexOf(@"\") + 1, pathName.IndexOf(".") - pathName.LastIndexOf(@"\") - 1);
}
catch (Exception e)
{
MessageBox.Show("获取文件"+e.Message.ToString());

}
return processName;
}

/// <summary>
///通过程序名查找对应进程,返回查找的结果或者程序状态
/// </summary>
/// <param name="exeName"></param>
/// <returns></returns>
public string findProcess(string exeName)
{
Thread.Sleep(1000);
string path="";//进程路径
Process[] process = Process.GetProcessesByName(exeName);
// MessageBox.Show(process.Length.ToString());
if (process.Length>0)
{
foreach (Process p in process)
{
try
{
path = p.MainModule.FileName.ToString();
// MessageBox.Show(path);
}
catch (Exception e)
{

MessageBox.Show("获取进程集合" + e.ToString());
}
}

}
if (process.Length == 0)
{
return System.DateTime.Now.ToString() + ":" + exeName + ".exe 未找到进程";
}
else if(process.Length >0)
{

Process p = process[0];

if (p.Responding)
{
//进程总线程数
int thSumCount = p.Threads.Count;
//线程无响应数量
int suspendCount = 0;

foreach (ProcessThread t in p.Threads)
{

//进程处于等待状态
if (t.ThreadState == System.Diagnostics.ThreadState.Wait)
{
//等待原因为挂起
if (t.WaitReason == ThreadWaitReason.Suspended)
{
suspendCount++;
}
}
//除了一个异常报错的对话框线程,其他线程都挂起了,说明进程已经卡死
if (thSumCount > 1 && thSumCount == suspendCount + 1)
{
return date + exeName + ".exe 程序卡死无响应,总线程:" + thSumCount + " " + "挂起线程:" + suspendCount;
}
else
{
// return System.DateTime.Now.ToString() + ":" + exeName + ".exe 程序正常运行";
}

}
}

}
return "";
}
//创建文件
public bool createFile(string filePath)
{
//创建文件
if (!File.Exists(filePath))
{
using (FileStream fileStream = File.Create(filePath)) {

};
}

return !File.Exists(filePath)?false:true;
}
/// <summary>
/// 读取文件,返回一个string类型的list集合
/// </summary>
/// <param name="filePath"></param>
/// <returns>list集合</returns>

public List<string> readFile(string filePath)
{
int cnt = 0;
List<string> list = new List<string>();
try
{
// 创建一个StreamReader对象来读取文件
using (StreamReader sr = new StreamReader(filePath))
{
string line;
// 逐行读取文件,直到读取完毕
while ((line = sr.ReadLine()) != null)
{
// 在这里处理每一行,例如打印到控制台
Console.WriteLine(line);
list.Add(line);
cnt++;
}
sr.Close();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
finally
{

}
return list;
}

//删除已添加的程序
public bool deleteFile(string path,string text)
{

bool flag = false;
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite,FileShare.ReadWrite);
StreamReader sr = new StreamReader(fs, Encoding.UTF8);
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
//读取文件内容
List<string> lines = new List<string>();
string line;
while ((line = sr.ReadLine()) != null)
{
if (text != getProcessName(line))
{
lines.Add(line.ToString());
}
}

fs.SetLength(0);
// MessageBox.Show("lines"+lines.Count.ToString());
foreach (var tex in lines)
{

if (tex != "")
{
// MessageBox.Show("添加");
// insertFile(path, tex);
sw.WriteLine(tex.Trim());
}
}
lines.Clear();//清空集合
sw.Close();
sr.Close();
fs.Close();
if (readFile(path, text) != true)
{
flag = true;

}
return flag;
}
/// <summary>
/// 读取文件 根据count判断返回多少行
/// </summary>
/// <param name="filePath"></param>
/// <param name="count"></param>
/// <returns></returns>
public int readFile(string filePath,int count)
{
int cnt = 0;
try
{
// 创建一个StreamReader对象来读取文件
using (StreamReader sr = new StreamReader(filePath))
{
string line;
// 逐行读取文件,直到读取完毕
while ((line = sr.ReadLine()) != null)
{
// 在这里处理每一行,例如打印到控制台
Console.WriteLine(line);
cnt++;
if (cnt==count)
{
break;
}
}
sr.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{

}
return cnt;
}
/// <summary>
/// 判断文本文件中是否存在这行数据
/// </summary>
/// <param name="filePath"></param>
/// <param name="text"></param>
/// <returns></returns>
public bool readFile(string filePath, string text)
{
bool flag = false;
try
{
// 创建一个StreamReader对象来读取文件
using (StreamReader sr = new StreamReader(filePath))
{
string line;
// 逐行读取文件,直到读取完毕
while ((line = sr.ReadLine()) != null)
{
// 在这里处理每一行,例如打印到控制台
if (text == getProcessName(line))
{
flag = true;
break;
}
}
sr.Close();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
finally
{

}
return flag;
}
/// <summary>
/// 启动程序
/// </summary>
/// <param name="path">程序路径</param>
public void startProcess(string path)
{
Thread.Sleep(500);
//MessageBox.Show(logPath);
try
{
if (findProcess(path) == "")
{
MessageBox.Show(path+".exe 已存在!");
return;
}
else
{

File.WriteAllText(logPath, date+ File.ReadAllText(logPath).Insert(0, "开始启动进程"+path + ".exe\r\n"));
Process.Start(path);
if (findProcess(path) == "")
{

File.WriteAllText(logPath, date + File.ReadAllText(logPath).Insert(0, "启动进程" + path + ".exe成功" + "\r\n"));
}
else
{

}
}



}
catch (Exception e)
{

MessageBox.Show(e.Message.ToString());
}
}
/// <summary>
/// 杀死进程
/// </summary>
/// <param name="processName">进程名</param>
public void killProcess(string processName)
{
try
{
Process[] process = Process.GetProcesses();
if (findProcess(processName) == "")
{
foreach (Process item in process)
{
if (item.ProcessName == processName)
{
item.Kill();
File.WriteAllText(logPath, File.ReadAllText(logPath).Insert(0, processName+".exe 进程已结束" + "\r\n")) ;
}
}
}
else
{

File.WriteAllText(logPath, date+File.ReadAllText(logPath).Insert(0, "进程未启动" + "\r\n"));
}


}
catch (Exception e)
{

MessageBox.Show("结束进程:"+e.Message.ToString());
}
}
}
}

 

posted @   菜鸟程序员lxs  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示