How do I find out what process Id and thread id / name has a file open
Posted
by peter
on Stack Overflow
See other posts from Stack Overflow
or by peter
Published on 2010-04-21T02:52:37Z
Indexed on
2010/04/21
2:53 UTC
Read the original article
Hit count: 353
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
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, but I want to prove it. 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.
© Stack Overflow or respective owner