Saturday, 10 February 2007

FileInfo.OpenRead vs FileInfo.OpenText

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 object

using (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: