This post will discuss how to check if a file is empty in C#.

You can determine if a file is empty or not using the return value of the FileInfo.Length property. The FileInfo.Length property returns the size of the current file, in bytes. If the specified file is empty, it returns 0 bytes.

Download Code

 
If the specified file does not exist, the System.IO.FileNotFoundException is raised. You can avoid the exception by checking whether the file exists before operating upon it, using the FileInfo.Exists property.

Download Code

 
Note that the FileInfo.Length method might return a non-zero length in some cases when only the byte order mark (BOM) character is left on the file. You may want to add subsequent validations to avoid risking non-deterministic behavior later. The idea is to read the contents of a file into a string using the File.ReadAllText() method and check the string length. Since the File.ReadAllText() method reads all the text in the file into a string, you should invoke this method only if the size returned by the FileInfo.Length property is single-digit. The following example illustrates.

Download Code

That’s all about checking if a file is empty in C#.