0

How to deal with the this Exception. I have a text file. And this code rewrites the file every 3 sec. At the same time another MS Excel file reads the data from the file. And sometimes I get this exception.

Is there a way for StreamWriter to wait until MS Excel finishes reading the file and start rewriting the file right after that?

string path = @"C:\My Path\my_file.txt";

 using (StreamWriter fs = new StreamWriter(File.OpenWrite(path)))
  {
    fs.Write(text);
    fs.Close();
  }
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Totallama
  • 418
  • 3
  • 10
  • 26

1 Answers1

-1

This is one way:

string path = @"C:\My Path\my_file.txt";
string text = "Declare text variable so this code compiles";
FileStream fileS = null;
bool done = false;
while (!done)
{
    done = true;

    try
    {
        fileS = File.OpenWrite(path);
    }
    catch (IOException ex)
    {
        done = false;
    }
}

using (StreamWriter fs = new StreamWriter(fileS))
{
    fs.Write(text);
    fs.Close();
};

I would also add in a StopWatch call to have the above while loop timeout after so long, and possibly a small Thread.Sleep() so you don't spin at full speed while essentially trying to obtain the FileStream lock.

Quantic
  • 1,779
  • 19
  • 30