I'm working on a Form
application which is suppose to run on multiple machines in one network at once. There is a Form in my application (let's call it Form1
) from which you can edit a XML
file located on the network. In order to prevent this file from being overwritten I have to make sure that only one person at a time can access Form1
.
My first try was to create an attribute inside the XML
file to indicate when someone is already accessing Form1
. The problem with that solution was that in the case of a sudden crash like a power outage the attribute would not be changed back to its normal value because Form1
was never properly exited. So you would have to manually change the value inside the XML
file.
My current solution is running a thread inside Form1
which is constantly reading a file until Form1
is closed again. And checking if the file is already being read before allowing other people to access Form1
. This solution works fine but it's not pretty since I have to have an additional file which sole purpose is to be read since I can't constantly read the XML
file itself without causing other problems.
Edit: Since the first answers are the same as my current solution here is the code of my current solution.
//CODE INSIDE FORM1
//Create thread which is reading File2
Thread readerThread = new Thread(new ThreadStart(ReadFile2));
readerThread.Start();
private void ReadFile2()
{
using (FileStream stream = File.Open(pathFile2, FileMode.Open, FileAccess.Read, FileShare.None))
{
//Wait until Form1 is being closed
threadWait.WaitOne();
stream.Close();
}
}
//CODE BEFORE ACCESSING FORM1
private bool Form1OpenCheck()
{
//Check if file2 is being read
bool noAccess = false;
try
{
using (FileStream stream = File.Open(pathFile2, FileMode.Open, FileAccess.Read, FileShare.None))
{
stream.Close();
}
}
catch (IOException)
{
noAccess = true;
}
return noAccess;
}
I would appreciate it if anyone has a better solution for this problem. Thanks.