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 に答える