D
Dougel Beilby
I'm trying to do what I'd thought would be an extremly
simple disk operation. Writing a number of lines of text
to a text file.
My problem occurs when trying to handle an Out of Disk
Space Exception. The following is a simplified snippet
that shows my problem.
<C# code snippet>
StreamWriter sw = File.CreateText(@"A:\Test.txt");
try
{
for (int i=0; i<100; i++)
{
sw.WriteLine("Some text gets writen here.");
}
sw.Flush();
sw.Close();
}
catch(Exception)
{
// Want to close and then delete the empty file here.
MessageBox.Show("Caught an exception");
}
<End C# code>
When I catch the exception, I want to be able to close
off the file, and then delete the empty file created.
What happens is that any attempt to close the file causes
another exception as .NET trys to the flush the buffer to
disk. And if I don't close the file, I can't delete it,
and the garbage collector will trigger the exception
again some random time after the code leaves scope.
I can prevent the garbage collection causing another
exception by suppressing finalization, but thats rather
ugly, and still doesn't allow me to remove the file.
I've tried varients like using a FileStream, and writing
the text out byte by byte, but still get the same
behaviour.
Any suggestions appreciated.
Dougal.
simple disk operation. Writing a number of lines of text
to a text file.
My problem occurs when trying to handle an Out of Disk
Space Exception. The following is a simplified snippet
that shows my problem.
<C# code snippet>
StreamWriter sw = File.CreateText(@"A:\Test.txt");
try
{
for (int i=0; i<100; i++)
{
sw.WriteLine("Some text gets writen here.");
}
sw.Flush();
sw.Close();
}
catch(Exception)
{
// Want to close and then delete the empty file here.
MessageBox.Show("Caught an exception");
}
<End C# code>
When I catch the exception, I want to be able to close
off the file, and then delete the empty file created.
What happens is that any attempt to close the file causes
another exception as .NET trys to the flush the buffer to
disk. And if I don't close the file, I can't delete it,
and the garbage collector will trigger the exception
again some random time after the code leaves scope.
I can prevent the garbage collection causing another
exception by suppressing finalization, but thats rather
ugly, and still doesn't allow me to remove the file.
I've tried varients like using a FileStream, and writing
the text out byte by byte, but still get the same
behaviour.
Any suggestions appreciated.
Dougal.