问题
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();
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;
I initialize item by calling a sub containing that item.modified = false. After checking that the file exist, I used a streamreader to read the lines of the file one by one until it finds a specific line and stops. The problem is when it checked if the file exist and doesn't find the specific line. It returns null even tough I initialize item to false and set it to false when it doesn't find the line. Note: this occurs seldom and works fine when I access other files to read and even in the same file that it returns null.
Note: Another problem I encountered is that it skips a line that it reads.
What could be the cause of this?
回答1:
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;
...
}
}
回答2:
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;
}
}
}
回答3:
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();
来源:https://stackoverflow.com/questions/4122514/null-reference-exception-in-c-sharp