-3

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.

TaW
  • 48,779
  • 8
  • 56
  • 89
marcuthh
  • 509
  • 9
  • 35
  • "The text file can be opened for viewing via button click once it has been created" How are you viewing the file? That might also be a problem... – Idle_Mind Aug 02 '15 at 15:05

1 Answers1

3

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);
    }
}
Daniel Rusznyak
  • 913
  • 8
  • 23
  • Thanks for this, does this need to be part of the `StreamWriter` variable used to write to the file? @Dracor – marcuthh Aug 02 '15 at 14:18
  • `File.Open()` returns a `FileStream` object that you can then insert into the StreamWriter. I.e. ` using (var f = File.Open("file.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) { using(var writer = new StreamWriter(f)) { writer.Write(data); } } ` – Daniel Rusznyak Aug 02 '15 at 14:43
  • Just tried this, it doesn't throw an error but it also doesn't actually write any of the new data to the file for some reason. Have you any idea why this might be? @Dracor – marcuthh Aug 02 '15 at 16:52
  • You might need to call `writer.Flush()' before leaving the inner scope. – Daniel Rusznyak Aug 02 '15 at 17:38