在这个课程中,我正在观看一个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.
答案 0 :(得分:2)
尝试明确设置,如何打开/共享文件(假设文件存在,但无论如何好的想法是将此区域包装在 try / catch 块中)。
using (var stream = new StreamReader( File.Open(_file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
{
string str = stream.ReadToEnd();
int x = str.LastIndexOf('\n');
string lastline = str.Substring(x + 1);
}