-1

在这堂课中,我正在观看一个 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.

4

1 回答 1

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);                              
     }
于 2013-09-13T22:53:33.220 回答