I have an application that compresses a bunch of text files. I currently have code like this (cut-out snippet):
FileInfo info = new FileInfo(...)
if (info.Length > 0) {
string content = getFileContents(...);
Debug.Assert(!string.IsNullOrEmpty(contents));
}
private string getFileContents(string filename)
{
TextReader reader = null;
string text = "";
try
{
reader = new StreamReader(filename);
text = reader.ReadToEnd();
}
catch (IOException e)
{
text = "";
}
finally
{
if (reader != null)
{
reader.Close();
}
}
return text;
}
Why am I getting an error message? The FileInfo.Length attribute has already been used to verify that the file is not empty.
Edit: This seems to be a mistake - I catch IO exceptions and return an empty string. But because of the discussion around fileInfo.Length (), there is something interesting here: fileInfo.Length returns 2 for an empty text-only BOM marker file (created in Notepad).
source
share