Sunday, 7 May 2017

c# - Why am I getting the Exception Object reference not set to an instance of an object

I have the following method:



public string GetReadersAsListXML()
{
StringBuilder sbXML = new StringBuilder();


sbXML.Append("" + "\r\n");

string filePath = ConfigurationManager.AppSettings["RFIDScannerConfiguration"];

XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.IgnoreComments = true;

using (XmlReader reader = XmlReader.Create(filePath, readerSettings))
{

while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.LocalName == "add")
{
int ListenerNumber = 1;

string Key = reader.GetAttribute("key");
Key = Key.Remove(Key.Length - 3);

string Value = reader.GetAttribute("value");

if (Key == "Active")
{

sbXML.Append("" + "\r\n");
sbXML.Append("Listener" + ListenerNumber + "" + "\r\n");
sbXML.Append("" + "\r\n");
ListenerNumber++;
}


sbXML.Append("" + "\r\n");
sbXML.Append("" + Key + "" + "\r\n");
sbXML.Append("" + "\r\n");
sbXML.Append("
" + "\r\n");
}
}
}

}


return sbXML.ToString();
}


Which I am using to parse an XML file.



I want to remove the last 3 characters of the string 'Key'.



However, I am getting the following error:




'Object reference not set to an instance of an object'.


I have used the .remove method in exactly the same way previously and it worked fine.



I know it is the line:



Key = Key.Remove(Key.Length - 3);



Causing the problem, but why, it is setup properly?

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...