In my program I have a chunk of code that does
var lines = File.ReadAllLines(myFileName);
if (lines[0] != null)
{
//does a few things
File.WriteAllLines(myFileName, lines);
}
While this worked fine at first, recently it has given me an exception due to the file being used by another process ~90% of the time. This already made no sense to me since File.ReadAllLines()
is supposed to close the file after reading. I added System.Threading.Thread.Sleep(3000)
right before the File.WriteAllLines()
, which increased my success rate to ~50%. Is sleeping the thread and crossing my fingers really my only option? I can not find any sources where people have had similar issues with File.ReadAllLines()
.
Any suggestions, explanation, or practical fixes would help. I can't help but feel like I'm missing something.
EDIT: edited my if statement with the actual code, incase it matters
EDIT: I am reading and writing the file to a network share, not my local machine.
EDIT: It does not appear to be any kind of hung version of my app holding on to the file, and from what I can tell by using the FileUtil class in this question, it is my app that has a lock on the file.