all groups > dotnet clr > june 2005 >
You're in the

dotnet clr

group:

Handling "out of disk space" with System.IO.StreamWriter



Handling "out of disk space" with System.IO.StreamWriter Marcus Ogden
6/14/2005 12:04:01 AM
dotnet clr: When writing a file using StreamWriter, I'm having difficulty handling the
"out of disk space" IOException. When catching this exception:

- if I call Close() on the StreamWriter, it fails with the same IOException
("There is not enough space on the disk.")
- if I call File.Delete(), it fails with another IOException ("The process
cannot access the file... because it is being used by another process.")

Any suggestions? Sample code below:

private bool HandleRunningOutOfDiskSpaceTest()
{
string filename = @"e:\output.txt"; // e: is an almost full USB
disk
StreamWriter writer = new StreamWriter(filename, false,
System.Text.Encoding.UTF8);

try
{
while (true)
{
writer.Write("0");
}
}
catch
{
try
{
writer.Close();
File.Delete(filename);
}
catch
{
MessageBox.Show("Failed to clean up after running out of
disk space.");
return false;
}
}

MessageBox.Show("Success!");
return true;
}

Marcus Ogden
Software Development
QSR International Pty Ltd
Melbourne, Australia
RE: Handling "out of disk space" with System.IO.StreamWriter john conwell
6/15/2005 8:37:06 AM
Hey Marcus,
One way to get around this is to use Win32 API CreateFile to create the
file. Use the returning handle to create a FileStream. use the FileStream
to create your StreamWriter (or just write directly to the FileStream).
Then, in order to close the file you are using call the Win32 API CloseHandle
on the file handle.

When you close a FileStream or StreamWriter, it tries to flush the contents
in its buffer to file. If you call CloseHandle on the file handle, the file
just gets closed without the flush.

[quoted text, click to view]
Re: Handling "out of disk space" with System.IO.StreamWriter Inge Henriksen
7/9/2005 12:00:00 AM
Why don't you check if there is enough disk space before you do the
writings, and notify the user if there is not enough space?
Look into System.Management.ManagementClass("Win32_LogicalDisk") for more
information abot doing this.


"Marcus Ogden" <MarcusOgden@discussions.microsoft.com> skrev i melding
news:2674B503-C853-4FEF-BE52-3E72A2CC0822@microsoft.com...
[quoted text, click to view]


Re: Handling "out of disk space" with System.IO.StreamWriter Mattias Sjögren
7/10/2005 12:00:00 AM

[quoted text, click to view]

Even if there's enough disk space at the time he does that check,
there might be less by the time he actually writes the file.



Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
AddThis Social Bookmark Button