I have a network consisting of multiple computers, for simplicity take two, Computer_A and Computer_B. On one of those, Computer_A, lies a text file with settings. One process on Computer_B should write some lines to that text file. Another process on Computer_A should monitor the file for changes, and when such a change occurs, read in the lines. Here is important that the process on Computer_A can be sure that the file has be written completely and it doesn't read half-written lines.
What I have is:
-> For Computer_B, which does the writing:
using (FileStream fileStream = new FileStream(@"file_on_computer_A", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read))
{
using (StreamWriter WriteToFile = new System.IO.StreamWriter(fileStream))
{
WriteToFile.WriteLine("setting one");
WriteToFile.WriteLine("setting two");
//...
}
}
-> Computer_A, uses FileSystemWatcher
to monitor changes to the file
FSW = new FileSystemWatcher();
FSW.Path = @"local_directory_path";
FSW.Filter = "PLSanDM.txt";
FSW.Changed += new FileSystemEventHandler(PLSanDM);
FSW.EnableRaisingEvents = true;
and as for the reading itself when the Event FSW.Changed
fires:
void PLSanDM(object sender, FileSystemEventArgs e)
{
using (FileStream fs = new FileStream(@"path_to_file", FileMode.Open, FileAccess.Read))
{
using (ReadFromFile = new System.IO.StreamReader(fs))
{
List<string> linesInFile = new List<string>();
string line;
while ((line = ReadFromFile.ReadLine()) != null)
{
linesInFile.Add(line);
}
foreach (string s in linesInFile)
{
//do sth
}
}
}
}
This however leads to a Exception
stating that the file is currently used by another process and it cannot be opened.
What am I doing wrong that leads to the exception and what is a correct solution? What do I have to change to make sure Computer_A can only read the file after Computer_B has finished writing it and not during the writing?