61

How do I check if a file is empty in C#?

I need something like:

if (file is empty)
{
    // do stuff
}

else
{
    // do other stuff
}
Lauren Rutledge
  • 1,195
  • 5
  • 18
  • 27
Arcadian
  • 1,373
  • 4
  • 20
  • 30
  • 1
    I would highly recommend checking out the answer below by @tee-dee, which actually provides a much more accurate way for determining if a file is truly empty or not in case you are dealing with text files. Most of the answers here are pretty much about using the `FileInfo.Length` which is correct but don't highlight one issue with it when dealing with files ending up containing Byte Order Mark (BOM). – Ayan May 14 '20 at 02:37

9 Answers9

132

Use FileInfo.Length:

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

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

tanascius
  • 53,078
  • 22
  • 114
  • 136
22

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;
}
TDao
  • 514
  • 4
  • 13
  • 5
    Surprised to see no one gave any attention to this answer which provides much needed valuable information regarding a shortcoming of the `FileInfo.Length` property and also a very good way to check if the file is truly empty or not. +1. – Ayan May 14 '20 at 01:51
11

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.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • 7
    For the OP's program, these issues might not be a concern. "The perfect is the enemy of the good." – Brian Jun 09 '10 at 16:34
8
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;
} 
Lauren Rutledge
  • 1,195
  • 5
  • 18
  • 27
Mike
  • 5,918
  • 9
  • 57
  • 94
6

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.

coole106
  • 61
  • 1
  • 1
  • 1
    I came across this answer while reviewing posts. Welcome, this is good first post. I would enhance it by perhaps adding a link to some documentation or other resource that explains why your answer is a good solution – Dan Beaulieu Jun 25 '15 at 19:58
3

This is how I solved the problem. It will check if the file exists first then check the length. I'd consider a non-existent file to be effectively empty.

var info = new FileInfo(filename);
if ((!info.Exists) || info.Length == 0)
{
    // file is empty or non-existant    
}
Walter Stabosz
  • 7,447
  • 5
  • 43
  • 75
3

In addition to answer of @tanascius, you can use

try
{
    if (new FileInfo("your.file").Length == 0)
    {
        //Write into file, i guess    
    }
} 
catch (FileNotFoundException e) 
{
    //Do anything with exception
}

And it will do it only if file exists, in catch statement you could create file, and run code agin.

miguelmpn
  • 1,859
  • 1
  • 19
  • 25
ArsenArsen
  • 312
  • 6
  • 16
2

What if file contains space? FileInfo("file").Length is equal to 2.
But I think that file is also empty (does not have any content except spaces (or line breaks)).

I used something like this, but does anybody have better idea?
May help to someone.

string file = "file.csv";
var fi = new FileInfo(file);
if (fi.Length == 0 || 
    (fi.Length < 100000 
     && !File.ReadAllLines(file)
        .Where(l => !String.IsNullOrEmpty(l.Trim())).Any()))
{
    //empty file
}
  • 3
    Instead of `IEnumerable.ToList().Count == 0` you could use `!IEnumerable.Any()`. Avoid to read the entire list. – Jérémie Bertrand Sep 07 '15 at 14:13
  • Works great for me! – Nerrolken Jun 02 '18 at 23:02
  • 1
    FWIW, if an application considers such a file to be "empty", then it probably shouldn't have been written that way in the first place. The writing process should have appropriately "trimmed" the content before writing. (If reading files from arbitrary sources, then there could be such blank content - but IMHO that is usually best handled in memory, AFTER reading the file - this is an obscure situation.) – ToolmakerSteve May 20 '21 at 19:23
0

You can use this function if your file exists and is always copied to your debug/release directory.

/// <summary>
/// Include a '/' before your filename, and ensure you include the file extension, ex. "/myFile.txt"
/// </summary>
/// <param name="filename"></param>
/// <returns>True if it is empty, false if it is not empty</returns>
private Boolean CheckIfFileIsEmpty(string filename)
{
    var fileToTest = new FileInfo(Environment.CurrentDirectory + filename);
    return fileToTest.Length == 0;
}
Lauren Rutledge
  • 1,195
  • 5
  • 18
  • 27
Kyle
  • 1