I have a c# windows form application that writes results to a text file. This is done by clicks on different buttons at their respective times, that all run functions to add specific text to the file.
The text file can be opened for viewing via button click once it has been created (as requested by my user), the only problem is that when the next button click tries to write to the file, it throws an exception because the file is already being used by another process.
Ideally, what I would like to do is run a function that checks if the file is open, and then close it if it is found to be open.
I've had a look around stack overflow and various other websites, but can't find anything particularly relevant to this concept!
If anyone could offer up any advice, I'd really appreciate it.
Use the function File.Open("", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
(you can change the parameters according to need) to allow shared file access mode.
You can use it the easiest like
using (var f = File.Open("file.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
using (var writer = new StreamWriter(f))
{
writer.Write(data);
}
}