c# - C#中的Null引用异常

标签 c# streaming nullreferenceexception notepad

尝试从结构中返回值时遇到“空引用异常”。

这是代码:

AssetItem item = new AssetItem(); 

        item = initModified();

        bool found = false;
        int index = getIndex(barcode);
        string modifiedFile = filepath + "Modified\\" + dir + "\\" + index + ".asdt";

        if(File.Exists(modifiedFile))
        {   
            using(StreamReader reader = new StreamReader(modifiedFile))
            {
                string line = reader.ReadLine();
                while(line.Trim()!="")
                {
                    string[] split = line.Split(',');
                    if(split[1]==barcode)
                    {
                        found = true;
                        break;
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
            }
        }

        if(found)
        {
            item.modified = true; 
        }
        else
        {
            item.modified = false;
        }


        return item;


我通过调用包含该item.modified = false的子项来初始化item。在检查文件是否存在之后,我使用了流读取器来逐行读取文件的行,直到找到特定的行并停止为止。问题是当它检查文件是否存在并且找不到特定行时。即使我将item初始化为false,也很难返回它,否则返回null。注意:这种情况很少发生,并且当我访问其他文件进行读取时,即使在返回null的同一文件中,也可以正常工作。

注意:我遇到的另一个问题是它跳过了读取的一行。

这可能是什么原因?

最佳答案

在文件末尾,ReadLine()返回null-然后在不检查的情况下在其上调用.Trim()(在该项目不存在并且您一直读取文件的情况下)-因此,您需要添加一个空检查(请注意,我也已经移动了ReadLine,所以它始终发生):

using(StreamReader reader = new StreamReader(modifiedFile))
{
    string line;
    while((line = reader.ReadLine()) != null && line.Trim() != "") {
        ...
    }
}


请注意,以上代码(基于您的代码)将在第一个空行结束;我个人可能会跳过空行:

using(StreamReader reader = new StreamReader(modifiedFile))
{
    string line;
    while((line = reader.ReadLine()) != null) {
        if(line.Trim() == "") continue;
        ...
    }
}

关于c# - C#中的Null引用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4122514/

相关文章:

c# - 混合使用锁和互锁操作是否安全?

c# - 二维房间的程序生成

c# - 如何在 C# 中创建子类?

c# - 为什么 ResourceManager.GetResourceSet 在构建后的第一个请求中返回 null? (C#)

c# - 是否可以让 SLAB 与 Microsoft.Diagnostics.Tracing.EventSource 一起使用?

重定向 RTMP 请求

Iphone http流媒体视频问题

java - Twitter 流媒体 API : Tracking changing keywords

c# - 为什么将动态对象类型转换为对象会抛出空引用异常?

c# - 如何找出导致 NullReferenceException 的原因