What to do when lost stream blocks a file?

96 Views Asked by At

I've had this problem several times and until now not found a satisfying solution for it (restarting the computer is quite annoying if it takes 15 min to do so...):

When programming something with files, you have to use filestreams. The problem with them is (at least in C#) that they need to release the file again before you can access it from another place. As this is of course a good idea most of the time, it happened to me a few times that I forgot to release the file in the process of programming and debugging or the program crashed before the stream could be closed.

Is there any way to find and kill those streams using windows features or something like that? Problems like that occured in C# as well as in C++ (or C, I am not sure anymore).


From the answers I read, that this should not occur when the stream is handled properly. But what if I was to dumb to handle it right and the stream is not closed properly (because of whatever reason)? Is there a way to fix this while the PC is running?

2

There are 2 best solutions below

0
On

This should not be a problem.

When your application is running normally, you use a using block to ensure that unmanaged resources like these are properly released. This is necessary for any object that implements the IDisposable interface.

If that fails, the operating system will jump in and save your bacon. The OS automatically releases any file handles that a process had open when it terminates, so even if your application crashes, there is no issue.

0
On

Anything that implements the IDisposable interface (which includes Streams) should always be either enclosed in a using block or be a member of a class which in turn implements IDisposable itself (and the new Dispose() method will also call the member's Dispose() method). There ought to be a compiler warning for this, imo.

Do this, and your file locks will be released properly.