简体   繁体   中英

How to check if a text file is empty c#

How do I write an if statement to check if my text file is empty?

The if statement below doesn't work for my text file as my file size is not zero even though it is visually empty, because the encoding type of the text file is UTF-8 with BOM so its size is 3 bytes:

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

It seems like you want to check for a file of length 0 or a file of length three containing only a UTF-8 BOM:

long fileLen = new FileInfo("file").Length;
if (fileLen == 0 || (fileLen == 3 && File.ReadAllBytes("file").SequenceEqual(new byte[] { 239, 187, 191 }))) {
    /* Is empty */
}

What about this?

if (File.ReadAllText(filepath).Length == 0)
{
...
}

You can check like this your file is empty or not;

    string fileName = "file.txt";

    FileInfo info = new FileInfo(fileName);
    if(info.Length ==0){


    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM