简体   繁体   English

FileInfo.Length大于0但文件是否为空?

[英]FileInfo.Length is greater than 0 but File is Empty?

I have an application that crunches a bunch of text files. 我有一个应用程序来处理一堆文本文件。 Currently, I have code like this (snipped-together excerpt): 目前,我有这样的代码(剪下摘录):

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 a failed assert? 为什么我收到失败的断言? The FileInfo.Length attribute was already used to validate that the file is non-empty. FileInfo.Length属性已用于验证文件是否为空。

Edit: This appears to be a bug -- I'm catching IO exceptions and returning empty-string. 编辑:这似乎是一个错误 - 我正在捕获IO异常并返回空字符串。 But, because of the discussion around fileInfo.Length(), here's something interesting: fileInfo.Length returns 2 for an empty, only-BOM-marker text file (created in Notepad). 但是,由于围绕fileInfo.Length()的讨论,这里有一些有趣的东西:fileInfo.Length为一个空的,仅有BOM标记的文本文件(在记事本中创建)返回2。

You might have a file which is empty apart from a byte-order mark. 除了字节顺序标记之外,您可能有一个空文件。 I think TextReader.ReadToEnd() would remove the byte-order mark, giving you an empty string. 认为 TextReader.ReadToEnd()将删除字节顺序标记,为您提供一个空字符串。

Alternatively, the file could have been truncated between checking the length and reading it. 或者,文件可能在检查长度和读取之间被截断。

For diagnostic purposes, I suggest you log the file length when you get an empty string. 出于诊断目的,我建议您在获得空字符串时记录文件长度。

See that catch (IOException) block you have? 看到你有的catch (IOException)块? That's what returns an empty string and triggers the assert even when the file is not empty. 即使文件不为空,这也会返回一个空字符串并触发断言。

If I remember well, a file ends with end of file, which won't be included when you call ReadToEnd. 如果我记得很清楚,文件以文件结尾结束,当你调用ReadToEnd时不会包含该文件。

Therefore, the file size is not 0, but it's content size is. 因此,文件大小不是0,但它的内容大小是。

What's in the getFileContents method? getFileContents方法中有什么?

It may be repositioning the stream's pointer to the end of the stream before ReadToEnd() is called. 它可能是在调用ReadToEnd()之前将流的指针重新定位到流的末尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM