在这堂课中,我正在观看一个 txt 文件,并且每个新行都是句柄:如果第一个单词是Start
(第二个是文件名),我正在打开Wiresahrk
进程并开始捕获。如果它以我开头,Stop
我将杀死正在运行的进程(所有正在运行的进程都存储在列表中并与文件名相关联)
string _file = @"D:\file.txt";
public void startWatch()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = Path.GetDirectoryName(_file);
watcher.Filter = Path.GetFileName(_file);
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Changed += watcher_Changed;
watcher.EnableRaisingEvents = true;
}
public void watcher_Changed(object sender, FileSystemEventArgs e)
{
readLine();
}
private void readLastLine()
{
string lastLine = string.Empty;
using (StreamReader sr = new StreamReader(_file))
{
string str = sr.ReadToEnd();
int x = str.LastIndexOf('\n');
lastLine = str.Substring(x + 1);
}
validateString(lastLine);
}
private void validateString(string str)
{
string[] arr = str.Split(' ');
if (arr.Length != 2 && arr[0] != "start" && arr[0] != "stop" && arr[0] != "finish")
return;
Tshark tshark = new Tshark(arr[1]);
tshark.startCapturing(); // Start wireshark process and start capturing
}
在我从文件中读取最后一行后,一切正常,第二次尝试读取后发生错误:The process cannot access the file because it is being used by another process.