我的代码从表单应用程序获取数据,并将结果显示在列表框中,并将数据保存在文件中。接下来,当我加载代码时,它应该从文件中读取数据并填充列表框。我有一个System.FormatException输入字符串,格式不正确。
在我准备读取文件之前,代码一直有效。我已经删除了空格和美元符号,但问题仍然存在。请您提供任何帮助。
下面的我的FileIO类代码
public static class FileIO
{
const string path = "Customers.txt";
// writes data from the array to the file
public static void WriteData(List<Customer> customers)
{
FileStream fs = null;
StreamWriter sw = null;
try
{
// open the file for writing; overwrite old content
fs = new FileStream(path, FileMode.Create, FileAccess.Write);
sw = new StreamWriter(fs);
// write data
foreach (Customer item in customers)
sw.WriteLine(item.DisplayCustomersInfo("|"));
}
catch (Exception ex)
{
MessageBox.Show("Error while writing to the file: " +
ex.Message, ex.GetType().ToString());
}
finally
{
if (sw != null) sw.Close(); // also closes fs
}
}
// reads data from the file, puts in a list, and returns it
public static List<Customer> ReadData()
{
List<Customer> customers = new List<Customer>();
FileStream fs = null;
StreamReader sr = null;
string line; // for reading
string[] columns; // result from splitting the line
// open the file for reading and read number into data
try
{
fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read);
sr = new StreamReader(fs);
while (!sr.EndOfStream) // while there is data in the file
{
line = sr.ReadLine(); // read the next line
line.Trim();
columns = line.Split(','); // split line into substring from line with comma delimiters
Customer c = new Customer(Convert.ToInt32(columns[0]), columns[1], Convert.ToChar(columns[2]),
Convert.ToDecimal(columns[3].Remove(0, 1)));//this is where I think the problem is.
customers.Add(c);
}
}
catch (FormatException)
{
MessageBox.Show("File contains bad format data. Aborting reading");
}
catch (Exception ex)
{
MessageBox.Show("Error while reading the file: "
+ ex.Message, ex.GetType().ToString());
}
finally
{
// close the file if open
if (sr != null) sr.Close(); //file stream gets closed too
}
return customers;
}
}
下面是文本文件。
12345 | RRRRR | R | $ 58.05
12345 | RRRRR | R | $ 58.05
12345 | RRRRR | R | $ 58.05
12345 | RRRRR | R | $ 58.05
12345 | RRRRR | R | $ 58.05
12345 | CCCCC | C | $ 60.05
12345 | CCCCC | C | $ 60.05
12345 | CCCCC | C | $ 60.05
12345 | CCCCC | C | $ 60.05
12345 | CCCCC | C | $ 60.05
12345 | IIIII | I | $ 116.09
12345 | IIIII | I | $ 116.09
12345 | IIIII | I | $ 116.09
12345 | IIIII | I | $ 116.09
12345 | IIIII | I | $ 116.09
12345 | IIIII | I | $ 116.09
我用过,和;在使用|。作为分隔符之前。
我希望从文件中读取数据并填充列表框并添加更多数据。