-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?

Alex
  • 3,730
  • 9
  • 43
  • 94

1 Answers1

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);
Christos
  • 53,228
  • 8
  • 76
  • 108