How to release the file handle when FileStream.Close() throws?

G

Guest

Hi,

I have a problem that seems to be a bug in the .NET Framework. If I create
a new FileStream on a media that has limited disk space (I use a diskette to
simulate the problem), the FileStream is effectively created. Small (smaller
than the buffer size) Writes to the buffer are also executed with no errors.

However, when I try to Flush the data, an IOException is thrown. I catch it
and in my finally block, I try to .Close() my stream which will in turn try
to Flush the data and another exception is thrown.

So, I tried putting a try/finally block in the first finally (!) and when
the Exception is thrown from the .Close() call, I decided that I could set my
FileStream to null (I know it leaks a handle, but lets my process run).

However, when the GC kicks in, it tries to close the FileStream which, you
guessed it, throws the same IOException again.

My solution was to finally remove the finalizer for the FileStream object at
that point but this is very ugly. is there a way to Close the FileStream in
that situation?

Thanks,
Joël
 
D

David Browne

joel said:
Hi,

I have a problem that seems to be a bug in the .NET Framework. If I
create
a new FileStream on a media that has limited disk space (I use a diskette
to
simulate the problem), the FileStream is effectively created. Small
(smaller
than the buffer size) Writes to the buffer are also executed with no
errors.

However, when I try to Flush the data, an IOException is thrown. I catch
it
and in my finally block, I try to .Close() my stream which will in turn
try
to Flush the data and another exception is thrown.

So, I tried putting a try/finally block in the first finally (!) and when
the Exception is thrown from the .Close() call, I decided that I could set
my
FileStream to null (I know it leaks a handle, but lets my process run).

However, when the GC kicks in, it tries to close the FileStream which, you
guessed it, throws the same IOException again.

My solution was to finally remove the finalizer for the FileStream object
at
that point but this is very ugly. is there a way to Close the FileStream
in
that situation?

Joel,

Just set the FileStream bufferSize to 0. This is a .net managed buffer, and
the file system has additional buffering below this.

The bufferSize is really there to make higher-level classes like
BinaryWriter which use a lot of small writes perform better.

David
 
G

Guest

Hi David,

First, thank you for your quick reply.

However, this doesn't solve the problem. When I try to Close() the
FileStream, it still throws an IOException.

I will provide code on Monday when I get back to work.

Any other ideas?

Joël
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top