Check if file is empty in C#
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.IO; public class Example { public static void Main() { string path = @"C:\data.txt"; var f = new FileInfo(path); if (f.Length == 0) { Console.WriteLine("The file {0} is empty", f.Name); } else { Console.WriteLine("The file {0} is not empty", f.Name); } } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; using System.IO; public class Example { public static void Main() { string path = @"C:\data.txt"; var f = new FileInfo(path); if (!f.Exists) { Console.WriteLine("The file {0} does not exist", f.Name); } else if (f.Length == 0) { Console.WriteLine("The file {0} is empty", f.Name); } else { Console.WriteLine("The file {0} is not empty", f.Name); } } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System; using System.IO; public class Example { public static bool IsFileEmpty(string fileName) { var f = new FileInfo(fileName); return f.Length == 0 || f.Length < 10 && File.ReadAllText(fileName).Length == 0; } public static void Main() { string path = @"\data.txt"; if (IsFileEmpty(path)) { Console.WriteLine("The file is empty"); } else { Console.WriteLine("The file is not empty"); } } } |
That’s all about checking if a file is empty in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)