Null Reference exception in C#

人走茶凉 提交于 2019-12-02 07:10:40

And the end of the file, ReadLine() returns null - and you then call .Trim() on it without checking (in the scenario where the item isn't there and you read the file all the way through) - hence you need to add a null-check (note also I've moved the ReadLine so it happens consistently):

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

Note that the above code (based on yours) will end on the first empty line; personally I'd probably skip empty lines:

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

One problem that I can find in your code is that you don't need the following line:

reader.Close();

using automatically does this for you.

Furthermore, your looping condition should check EndOfStream instead of trimming the line.

i.e., Modifying your code to something like this:

using(StreamReader reader = new StreamReader(modifiedFile))
{

    while(!reader.EndOfStream)
    {
        string line = reader.ReadLine();
        string[] split = line.Split(',');
        if(split[1]==barcode)
        {
            found = true;
            break;
        }
    }
}

On a side note, why create a new instance then re-assign to it without using it for any purpose..

AssetItem item = new AssetItem();  
item = initModified();

Could become

AssetItem item =  initModified();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!