Is file empty check
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;
}
Use FileInfo.Length:
if( new FileInfo( "file" ).Length == 0 )
{
// empty
}
Check the Exists property to find out, if the file exists at all.