【问题标题】:c# input string was not in a correct format (how to deal with corrupted data?)c#输入字符串的格式不正确(如何处理损坏的数据?)
【发布时间】:2016-02-22 07:55:57
【问题描述】:

我正在创建一个 Windows 窗体,它使用 String.Compare 顺序搜索 3 个文件。如果文本框不为空,则首先按文本框字符串搜索,如果为空,则按公司字符串搜索。包含数字的文件有一些“损坏”的行,例如。 1345.2fd 我想通过使它们显示为“销售数据损坏”来处理这些问题,虽然我确实这样做了,但是当我运行程序时出现输入字符串错误。

第 42 行

salesData = decimal.Parse(salesFile.ReadLine().Trim());

【问题讨论】:

  • 在哪一行抛出这个?
  • 对不起我的错误:第 42 行 salesData = decimal.Parse(salesFile.ReadLine().Trim());
  • 使用 TryParse。您的文件数据格式不正确。 (可能有“,”而不是“。”?作为小数分隔符)
  • 使用decimal.TryParse代替decimal.Parse
  • 这个fd 部分一直存在吗?有没有可能得到另一个字符?

标签: c# string search


【解决方案1】:

你必须检查salesFile.ReadLine()是否为空。

decimal salesData = 0;
string s = salesFile.ReadLine();
if (s != null && decimal.TryParse(s.Trim(), out salesData))
{
    // True
}
else
{
    //Your data is error
}

另外:这也可能会出错,因为您不检查 null:

gamesData = gamesFile.ReadLine().Trim();  // <---- May cause Error
salesData = decimal.Parse(salesFile.ReadLine().Trim());  // <---- May cause Error
compData = compFile.ReadLine().Trim();  // <---- May cause Error

【讨论】:

    【解决方案2】:

    我认为您的问题是由 decimal.Parse() 函数触发的 FormatException。该函数排除了一个数字,但您的格式错误的字符串不是一个真实的数字,因此会引发异常。您最好使用 try-catch 并处理错误 参考:https://msdn.microsoft.com/en-us/library/cafs243z(v=vs.110).aspx

    【讨论】:

      猜你喜欢
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 2016-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多