Essentially the definition of FileInfo.OpenRead & FileInfo.OpenText look similar, both opens the file with read-only access. The difference is FileInfo.OpenRead returns a FileStream & FileInfo.OpenText returns StreamReader object. This gives a slight difference when you interact with the file, lets first look at the OpenRead's FileStream objectusing (FileStream fs = fi.OpenRead())
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b,0,b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
The FileInfo.OpenText methods StreamReader code looks like the following:
// Open the stream and read it back.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
I find the StreamReader makes it much easier to interact with the file.
No comments:
Post a Comment