Comment Resolution:
Application error caused by another problem
I read / write the file in 2 different applications, when the file is read or written, it will always be blocked by application A or B, and both of them use FileShare.None .
My problem is that even wrapping the reader around try / catch still causes the application to crash using an IOException on the line in use (does not happen with the author).
I also did catch as catch (IOException ... , which I believe has no meaning, moreover, makes it more readable.
What is the correct way to ignore when a file is locked and keep trying until the file is available?
while (true) { try { using (FileStream stream = new FileStream("test_file.dat", FileMode.Open, FileAccess.Read, FileShare.None)) { using (TextReader reader = new StreamReader(stream)) { // bla bla bla does not matter } } } catch { // bla bla bla does not matter again } Thread.Sleep(500); }
Record
private bool WriteData(string data) { try { using (FileStream stream = new FileStream("test_file.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) { stream.SetLength(0); using (TextWriter writer = new StreamWriter(stream)) { writer.Write(data); } } return true; } catch { return false; } }
Please note that I do not transfer the sharing rights (both the writer and the reader) to FileShare.None ) to anyone when the file is used for any process that it reads or writes, so I will handle the exception until the file is available which does not work.
source share