Beware of the FileInfo.OpenText() method
I’m a big fan of the System.IO.FileInfo object in .NET because it wraps the System.IO.File object nicely in a strongly typed way. It makes it easier to work with files. The FileInfo class has a method called OpenText that returns a StreamReader instance which can then be read into a string and other things.
If you use the OpenText method read the text of a file, then the easiest way is like so:
FileInfo fi = new FileInfo("C:\\currency.xml");
string content = fi.OpenText().ReadToEnd();
Now the content variable contains the text content of the currency.xml file, but there is a problem with this approach. Because the OpenText method creates a StreamReader instance which we then call the ReadToEnd method on, the StreamReader keeps a lock on the file. The can cause many problems and must be avoided.
Instead you could do like so, which releases the file handle when the StreamReader is disposed:
FileInfo fi = new FileInfo("C:\\currency.xml");
StreamReader reader = fi.OpenText();
string content = reader.ReadToEnd();
reader.Dispose();
This works fine, but we doubled the lines needed to read the text. This might not be an issue, but then we could just as well just use the StreamReader directly without using the FileInfo class like so:
using (StreamReader reader = new StreamReader("C:\\currency.xml"))
{
string content = reader.ReadToEnd();
}
It is much cleaner than using the FileInfo class and the intent is very clear as well.
Comments
Comments are closed