-1

In this class i am watching a txt file and every new line is handle: If the first word is Start (the second is the file name) i am opening Wiresahrk process and start capturing. If it start with Stop i am kill the process who running (all running processes stored in list and associate to the file name)

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
}

After i read the last line from my file everything works fine, after the second time i try to read an error occurs: The process cannot access the file because it is being used by another process.

Marc
  • 3,905
  • 4
  • 21
  • 37
user2214609
  • 4,713
  • 9
  • 34
  • 41

1 Answers1

2

Try explicitly setting, how file will be opened/shared (assuming file exists, but anyway good idea will by to wrap this region in try/catch block).

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);                              
     }
Dmytro
  • 1,590
  • 14
  • 14