加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – FileInfo.Length大于0但文件为空?

发布时间:2020-12-16 01:38:43 所属栏目:百科 来源:网络整理
导读:我有一个应用程序来处理一堆文本文件.目前,我有这样的代码(剪下摘录): FileInfo info = new FileInfo(...)if (info.Length 0) { string content = getFileContents(...); // uses a StreamReader // returns reader.ReadToEnd(); Debug.Assert(!string.IsNu
我有一个应用程序来处理一堆文本文件.目前,我有这样的代码(剪下摘录):

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;
    }

为什么我收到失败的断言? FileInfo.Length属性已用于验证文件是否为空.

编辑:这似乎是一个错误 – 我正在捕获IO异常并返回空字符串.但是,由于围绕fileInfo.Length()的讨论,这里有一些有趣的东西:fileInfo.Length为一个空的,仅有BOM标记的文本文件(在记事本中创建)返回2.

解决方法

看到你有的catch(IOException)块?即使文件不为空,这也会返回一个空字符串并触发断言.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读