-1

I have the following method:

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

        sbXML.Append("<items>" + "\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("<item>" + "\r\n");
                            sbXML.Append("<id>Listener" + ListenerNumber + "</id>" + "\r\n");
                            sbXML.Append("<attributes>" + "\r\n");
                            ListenerNumber++;
                        }

                        sbXML.Append("<attribute>" + "\r\n");
                        sbXML.Append("<code>" + Key + "</code>" + "\r\n");
                        sbXML.Append("<value><![CDATA[" + Value + "]]></value>" + "\r\n");
                        sbXML.Append("</attribute>" + "\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?

1
  • check if(Key != null) Commented Feb 4, 2015 at 15:46

1 Answer 1

0

Does the Key is not null? Certainly it is null. Hence you get this error.

In order to avoid this check this before you Remove that you want:

if(Key!=null && Key.Length>3)
    Key = Key.Remove(Key.Length - 3);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.