Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
381 views
in Technique[技术] by (71.8m points)

c# - Why Empty Text File Contains 3 bytes?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...