Is file empty check

Solution 1:

Use FileInfo.Length:

if( new FileInfo( "file" ).Length == 0 )
{
  // empty
}

Check the Exists property to find out, if the file exists at all.

Solution 2:

FileInfo.Length would not work in all cases, especially for text files. If you have a text file that used to have some content and now is cleared, the length may still not be 0 as the byte order mark may still retain.

You can reproduce the problem by creating a text file, adding some Unicode text to it, saving it, and then clearing the text and saving the file again.

Now FileInfo.Length will show a size that is not zero.

A solution for this is to check for Length < 6, based on the max size possible for byte order mark. If your file can contain single byte or a few bytes, then do the read on the file if Length < 6 and check for read size == 0.

public static bool IsTextFileEmpty(string fileName)
{
    var info = new FileInfo(fileName);
    if (info.Length == 0)
        return true;

    // only if your use case can involve files with 1 or a few bytes of content.
    if (info.Length < 6)
    {
        var content = File.ReadAllText(fileName);   
        return content.Length == 0;
    }
    return false;
}

Solution 3:

The problem here is that the file system is volatile. Consider:

if (new FileInfo(name).Length > 0)
{  //another process or the user changes or even deletes the file right here

    // More code that assumes and existing, empty file
}
else
{


}

This can and does happen. Generally, the way you need to handle file-io scenarios is to re-think the process to use exceptions blocks, and then put your development time into writing good exception handlers.

Solution 4:

if (!File.Exists(FILE_NAME))
{
    Console.WriteLine("{0} does not exist.", FILE_NAME);
    return;
}

if (new FileInfo(FILE_NAME).Length == 0)  
{  
    Console.WriteLine("{0} is empty", FILE_NAME);
    return;
} 

Solution 5:

I've found that checking the FileInfo.Length field doesn't always work for certain files. For instance, and empty .pkgdef file has a length of 3. Therefore, I had to actually read all the contents of the file and return whether that was equal to empty string.