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.
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.
An empty file contains nothing, it is empty. So it contains 0 bytes.
An empty file really has size zero.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With