0

我正在编写应该从文本文件中读取数据的简单方法。我不明白为什么这种方法只能读取第 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;
    }
4

2 回答 2

5

你打line = sr.ReadLine()了两次电话。

删除这一行,string str = sr.ReadLine();并使用变量line

于 2012-09-24T23:05:33.943 回答
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;
}
于 2012-09-24T23:16:10.250 回答