Hi All,
I am using C# in an application and am having some problems with a file becoming locked.
The piece of code does this,
while (true)
{
Read a packet from a socket (with data in it to add to the file)
Open a file // one of these randomly throws an exception saying that the file is locked
Writes data to it
Close a file
}
But in the process the file becomes locked. I don't really understand how, we are are definately catching and reporting exceptions so I don't see how the file doesn't get closed every time.
My best guess is that something else is opening the file. It is not likely to be another app, but it could be a different thread, but I just want to prove it either way. Can someone please provide a piece of code to check whether the file is open and if so report what processId and threadId has the file open.
For example if I had this code,
StreamWriter streamWriter1 = new StreamWriter(@"c:\logs\test.txt");
streamWriter1.WriteLine("Test");
// code to check for locks??
StreamWriter streamWriter2 = new StreamWriter(@"c:\logs\test.txt");
streamWriter1.Close();
streamWriter2.Close();
That will throw an exception because the file is locked when we try and open it the second time. So where the comment is what could I put in there to report that the current app (process Id) and the current thread (thread Id) have the file locked?
Thanks.