views:

329

answers:

4

I need to recover form an error case where a file gets left in a locked state. How can I in c# tell this file to reset it's locks? I need to add to this the file is opened by a 3rd party dll and I don't actually have access to the file handle.

A: 

You have to close the file using .Close(). You need to make sure you still have a way of accessing the file object.

You usually can avoid this error by writing a try{} ... finally {} construct after the code that does your file I/O. In the finally {} block, you'd call the Close method of your file object, preventing this condition. You can also use a using {} block when you create your files, and this will also take care of this problem.

Dave Markle
This would work if I wasn't opening the file in a 3rd party dll.
Erin
+4  A: 

Locking a file is the responsibility of the Operating System (on behalf of the program that opens it). If a file is left in a locked state, its really up to the OS to unlock. This typically happens automatically when the process that opened the file exits. There is, however, a really cool utility that I came across that will help.

Its called Unlocker

dviljoen
+1  A: 

I would really consider finding another 3rd party dll. Any system handling Streams should properly respond to error conditions and not leave things like file locks in place.

Is it possible that the library does provide error condition clean up, you've just over looked it? Try something like the following,

 try {
   thirdPartyObj = new ThirdPartObj();
   // Some possible error causing object actions
 catch(Exception ex) {
   thirdPartyObj = null; // The object should close its resources
 }
ShaneB
The process hangs and eats up 50% of the cpu. In other cases it will return an error code. It's an static function in a c++ dll.
Erin
+1  A: 

You could perhaps start a command line process like net or psfile with something along the lines of:

System.Diagnostics.Process.Start("psfile c:\myfile.txt -c");

You can get psfile here.

You could also use

net file ID /close

but that would require you to know the file ID, which would take a bit more work.

Untested but this should give you a starting point.

Harpua