代码之家  ›  专栏  ›  技术社区  ›  Fukkatsu

FormatException,将字符串转换为长字符串

  •  0
  • Fukkatsu  · 技术社区  · 10 年前

    我从一个XML文件中获取值,并将它们放在 dataGridView 。我成功地做到了这一点,但在我想操纵从XML文件中获得的数据之后,它不起作用,我得到了一个错误 Input string was not in a correct format. .

    我的目标是转换从XML文件捕获的数据并将其除以1024。没有 InnerText 我可以安全地转换成长字符串的字符串?我应该添加更多的代码来实现这一点吗?

    在调试期间,我打印出temp的值,值为53999759360,我也尝试不将其设置为ToString(),同样的错误

    这是我的代码的一部分:(大小的值是“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
                }
            }
    
    1 回复  |  直到 10 年前
        1
  •  3
  •   Trafz    10 年前

    恐怕你的代码工作正常。“temp”变量必须是字符串、空或空白。

    我创建了一个XmlDocument(来自XDocument,抱歉。我认为它更容易使用),看起来像您的目标并运行代码。它运行良好,并给出适当的值:

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

    编辑: 这里有一个更简单的方法来测试实际发生的情况:

    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