Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Empty Text File Contains 3 bytes?

Tags:

c#

.net

file

text

I'm using a text file inside my C# project in vs2010. I added to solution and set its "Copy Output" to "Copy Always". When I use the following codes, it gives me the text result with leading three bytes or in utf8 one byte. I looked at windows explorers file properties, its size appears 3 bytes.

public static string ReadFile(string fileName)
        {
            FileStream fs = null;
            try
            {
                fs = new FileStream(fileName, FileMode.Open);
                FileInfo fi = new FileInfo(fileName);
                byte[] data = new byte[fi.Length];
                fs.Read(data, 0, data.Length);
                fs.Close();
                fs.Dispose();
                string text = Encoding.ASCII.GetString(data);
                return text;
            }
            catch (Exception)
            {
if(fs != null)
{
    fs.Close();
    fs.Dispose();
}
return string.Empty;
            }
        }

Why is this like above? How can I read text files without StreamReader class?

Any helps, codes wil be very appreciated.

like image 956
Mesut Avatar asked Aug 29 '13 16:08

Mesut


People also ask

How many bytes is an empty text file?

If the file is an empty text file, it may indeed contain zero bytes. This number is important to programmers because we often need to open a file, read all the data, and close it.

What does an empty file contain?

An empty file contains nothing, it is empty. So it contains 0 bytes.

How large is a empty file?

An empty file really has size zero.


1 Answers

So, those three bytes you are seeing are the byte order marker for the unicode file I am guessing. For UTF-8, it is three bytes.

You can avoid those by saving the file using UTF-8 without signature.

like image 167
Darren Kopp Avatar answered Oct 05 '22 00:10

Darren Kopp