C# 尝试转换时出现格式异常

C# 尝试转换时出现格式异常,c#,visual-studio-2012,C#,Visual Studio 2012,所以我试图从一个文本文件中读取并将每个字段存储到一个数组中。但当我试图将accountNumber转换为Int时,我得到了一个错误 public bool matchCustomer(int accountID){ string[] data = null; string line = Global.currentFile.reader.ReadLine(); while (line != null) {

所以我试图从一个文本文件中读取并将每个字段存储到一个数组中。但当我试图将accountNumber转换为Int时,我得到了一个错误

     public bool matchCustomer(int accountID){
        string[] data = null;
        string line = Global.currentFile.reader.ReadLine();
        while (line != null)
        {
            data = line.Split('*');
            this.accountNumber = Convert.ToInt32(data[0]);
            line = Global.currentFile.reader.ReadLine();
            if (accountID == this.accountNumber)
            {
                return true;
            }

          }

        return false;
       }

这是因为数据[0]不能转换为整数。运行时数据[0]是什么

您可以使用:

int value;
if(Int32.TryParse(data[0], out value))
{
  accountNumber = value;
}
else
{
  //Something when data[0] can't be turned into an int.
  //You'll have to decide this logic.
}

很可能,因为您在字符串中按分隔符*拆分:

12345 * Shrek * 1209 * 100,000 * 50,000
您离开时留下的是一个空格数字“12345”,而不是所有的数字“12345”。这导致它无法转换。尝试应用修剪:

 this.accountNumber = Convert.ToInt32(data[0].Trim());
另外,要注意带有千位分隔符逗号的字符串(50000和100000)。如果无法转换,则可能需要将其替换为空字符串:

data[4].Replace(",","").Trim();

另外两个答案解决了这个问题并进行了修复,我想提供另一个选择,使用
Linq

您可以用此替换完整的
块内容

return line.Split('*').Select(s=> s.Trim().Replace(",", ""))
            .Where(c=> Regex.IsMatch(c.Trim(), @"\d+"))
            .Select(s=>int.Parse(s.Trim()))            
            .Any(e=>e == accountId);

工作时

发生了什么错误,数据[0]的值是多少?
?错误显示“输入字符串格式不正确”。数据[0]的值是12345。文本文件的第一行是12345*Shrek*1209*100000*50000如果值都是数字,是否有超过10位的值?(特别是,任何大于2147483647的值)我怀疑是空间问题,但通过控制台应用程序测试表明Convert.ToIn32(..)足够智能,可以修剪。但是,您认为它不能正确捕捉逗号是正确的。您可以测试它,这很好。:)我现在没带笔记本电脑。有时,这种看似正确的格式会给我们带来问题。:)