Search code examples
c#xmlxmldocumentformatexception

FormatException, converting a string to a long


I was getting values from an XML file and placing them inside a dataGridView. I was successful in doing so, but after I want to manipulate data that I got from an XML file, It does not work and i get an error of Input string was not in a correct format. .

My goal is to convert a data captured from an XML File and divide it by 1024. Ain't InnerText a string that I can safely convert to a long? should I add more code to make this work?

During my debugging, i printed out the value of temp and the Value is 53999759360, I also tried not making it ToString() , same error

Here is part of my code: (The value of size is "53999759360")

        XmlDocument doc = new XmlDocument();
        string xmlFilePath = @"C:\xampp\htdocs\userInfo.xml";
        doc.Load(xmlFilePath);

        XmlNodeList accountList = doc.GetElementsByTagName("account");

        foreach (XmlNode node in accountList)
        {
            XmlElement accountElement = (XmlElement)node;

            foreach (XmlElement dskInterface in node.SelectNodes("systemInfo/dskInfo/dskInterface"))
            {
                String temp = (dskInterface["size"].InnerText).ToString();
                long iasdas = Convert.ToInt64(temp) / 1024; // Error Happens here
            }
        }

Solution

  • I'm afraid that your code works fine. It must be that the "temp" variable is string.Empty or whitespace.

    I created an XmlDocument (from XDocument, sorry. I think it's a lot easier to work with) that looks like what you're targeting and ran your code. It runs fine and gives a proper value:

    var xDoc = new XDocument(
                new XDeclaration("1.0", "UTF-8", "no"),
                new XElement("root",
                    new XElement("account",
                        new XElement("systemInfo",
                            new XElement("dskInfo",
                                new XElement("dskInterface",
                                    new XElement("size", 53999759360)))))));
    
    var doc = new XmlDocument();
    using (var xmlReader = xDoc.CreateReader())
    {
        doc.Load(xmlReader);
    }
    
    
    XmlNodeList accountList = doc.GetElementsByTagName("account");
    
    foreach (XmlNode node in accountList)
    {
        XmlElement accountElement = (XmlElement)node;
    
        foreach (XmlElement dskInterface in node.SelectNodes("systemInfo/dskInfo/dskInterface"))
        {
            String temp = (dskInterface["size"].InnerText).ToString();
            long iasdas = Convert.ToInt64(temp) / 1024; // Error Happens here
        }
    }
    

    Edit: Here's an easier way to test what's actually happening:

    Convert.ToInt64(null); // Doesn't crash
    Convert.ToInt64(string.Empty); // Crashes
    Convert.ToInt64(""); // Will crash if you comment the line above
    Convert.ToInt64(" "); // Will crash if you comment the lines above