我收到此错误,虽然还有其他帖子,但我没有得到适当的解决方案来解决我的问题。
调试器指向此语句
id = Convert.ToInt32(s);
它在开始时工作正常但现在却产生了错误。以下是完整的功能。作为旁注,我在Visual Studio 2013中遵循N层架构。
public List<ATMBO> GetDataFromFile() // get data from file and store it into object and pass to BLL !!!!
{
List<ATMBO> l = new List<ATMBO>();
// opening stream !!!
FileStream f = new FileStream("BankClient.txt", FileMode.Open);
StreamReader sr = new StreamReader(f);
if (!File.Exists("BankClient.txt"))
{
Console.WriteLine("{0} does not exist.", "BankClient.txt");
}
// Start reading from file
string record=sr.ReadLine();
//sr.ReadLine();
while((record = sr.ReadLine()) != null)
{
//record = sr.ReadLine();
// storing data from file to object!!!!
string [] data = record.Split(':');
//Console.WriteLine(data[0]);
ATMBO bo = new ATMBO();
string s = (data[0]);
int id = 0;
try
{
id = Convert.ToInt32(s);
}
catch (FormatException e)
{
Console.WriteLine("Input string is not a sequence of digits.");
}
catch (OverflowException e)
{
Console.WriteLine("The number cannot fit in an Int32.");
}
bo.ID1 = id;
bo.Login = data[1];
bo.Type = data[2];
string ss = (data[3]);
int blnc = Convert.ToInt32(ss);
bo.Balance = blnc;
bo.Status = data[4];
bo.Date = data[5];
bo.Pin = data[6];
l.Add(bo);
}
sr.Close();
f.Close();
return l;
}
我的BankClient.txt
文件的内容:
ID:Name:Type:Balance:Status:Date:Pin
00:Admin:Savings:500:Active:1/11/2014:111
01:Nabeel:Savings:0:Active:1/11/2014:222
02:Asad:Current:600:Active:2/11/2014:333
03:Aqsa:Current:-300:Active:3/11/2014:ABC
04:Umer:Savings:1000:Active:4/11/2014:444
05:Ali:Savings:1000:Active:4/11/2014:555
答案 0 :(得分:1)
您需要在代码中添加一些错误处理,以确保您可以使用实际值,例如
string [] data = record.Split(':');
if(data.length < 7)
Console.WriteLine("Data doesn't contain what was expected");
更好的是,您可以使用Convert.ToInt32
TryParse
int id;
if(!int.TryParse(s, out id))
Console.WriteLine("Not a valid id");