Null Reference exception in C#

后端 未结 3 2051
慢半拍i
慢半拍i 2021-01-25 09:17

I\'m experiencing \"null reference exception\" when I\'m attempting to return a value from a structure.

here is the code:

AssetItem item = new AssetItem(         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-25 09: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;
            ...
        }
    }
    

提交回复
热议问题