FileInfo.Length is greater than 0, but the file is empty?

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(...);
        // uses a StreamReader
        // returns reader.ReadToEnd();
    Debug.Assert(!string.IsNullOrEmpty(contents)); // FAIL
}

private string getFileContents(string filename)
    {
        TextReader reader = null;
        string text = "";

        try
        {
            reader = new StreamReader(filename);
            text = reader.ReadToEnd();
        }
        catch (IOException e)
        {
            // File is concurrently accessed. Come back later.
            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).

+3
source share
4 answers

catch (IOException), ? assert, .

+2

, , . , TextReader.ReadToEnd() , .

, .

, .

+5

, , ReadToEnd.

, 0, .

0

getFileContents?

ReadToEnd().

0

Source: https://habr.com/ru/post/1769586/


All Articles