0

I am writing many .csv files to my hard drive to log some measurement data using the StreamWriter and CsvHelper from Josh Close class:

using (TextWriter writer = new StreamWriter(path,true))
using (CsvWriter = new CsvWriter(writer))
{
    writer.WriteLine("1...");
    /// ...
    /// ...
    /// ...
    writer.Flush();
}

Overnight their can be up to 500 MB of data stored. So today this question bothers me: What will happen if my hard drive or USB drive has no more empty space and I want to write a new file? And what is a best practice to prevent this situation? Will this throw an exception or not? I found nothing in the .NET documents about this situation.

DavidG
  • 113,891
  • 12
  • 217
  • 223

2 Answers2

1

It will throw a new IOException. You can check if the exception is disk full like this (disk full check taken from here)

try
{
    //Write stuff to disk
}
catch(IOException ex)
{
    if(IsDiskFull(ex))
    {
        //Disk is full
    }
}


public static bool IsDiskFull(Exception ex)
{
    const int ERROR_HANDLE_DISK_FULL = 0x27;
    const int ERROR_DISK_FULL = 0x70;

    int win32ErrorCode = Marshal.GetHRForException(ex) & 0xFFFF;
    return win32ErrorCode == ERROR_HANDLE_DISK_FULL || win32ErrorCode == ERROR_DISK_FULL;
}
Community
  • 1
  • 1
DavidG
  • 113,891
  • 12
  • 217
  • 223
0

You should keep separated rolling files, which older files can be deleted when your hard disk is becoming full (never wait for that to happen!).

Check remaining drive space vs. the data you need to write, and perform the deletion before you actually run out of space.

fabrosell
  • 614
  • 1
  • 8
  • 19