我正在编写应该从文本文件中读取数据的简单方法。我无法理解为什么这个方法只读取第2,第4,第6行?方法如下。我的代码出了什么问题?
public static List<Employee> ReadFromFile(string path = "1.txt")
{
List<Employee> employees = new List<Employee>();
Stream stream = null;
StreamReader sr = null;
try
{
stream = new FileStream(path, FileMode.Open, FileAccess.Read);
stream.Seek(0, SeekOrigin.Begin);
sr = new StreamReader(stream);
string line;
while ((line = sr.ReadLine()) != null)
{
Employee employee = new DynamicEmployee();
string str = sr.ReadLine();
employee.FirstName = str.Substring(1, 20).Trim();
employee.LasttName = str.Substring(20, 20).Trim();
employee.Paynment = Convert.ToDouble(str.Substring(40, 20).Trim());
Console.WriteLine("{0} {1} {2}", employee.FirstName, employee.LasttName, employee.Paynment);
employees.Add(employee);
//Console.WriteLine(str);
}
}
catch//(System.FormatException)
{
Console.WriteLine("File format is incorect");
}
finally
{
sr.Close();
stream.Close();
}
return employees;
}
答案 0 :(得分:5)
您正在拨打line = sr.ReadLine()
两次。
删除此行string str = sr.ReadLine();
并使用变量line
答案 1 :(得分:0)
它应该是这样的:
public static List<Employee> ReadFromFile(string path = "1.txt")
{
List<Employee> employees = new List<Employee>();
Stream stream = null;
StreamReader sr = null;
try
{
stream = new FileStream(path, FileMode.Open, FileAccess.Read);
stream.Seek(0, SeekOrigin.Begin);
sr = new StreamReader(stream);
string line;
while ((line = sr.ReadLine()) != null)
{
Employee employee = new DynamicEmployee();
// string str = sr.ReadLine(); // WRONG, reading 2x
employee.FirstName = line.Substring(1, 20).Trim();
employee.LasttName = line.Substring(20, 20).Trim();
employee.Paynment = Convert.ToDouble(line.Substring(40, 20).Trim());
Console.WriteLine("{0} {1} {2}", employee.FirstName, employee.LasttName, employee.Paynment);
employees.Add(employee);
//Console.WriteLine(str);
}
}
catch//(System.FormatException)
{
Console.WriteLine("File format is incorect");
}
finally
{
sr.Close();
stream.Close();
}
return employees;
}