2012-09-24 55 views
0

我正在寫簡單的方法,應該從文本文件中讀取數據。我不明白爲什麼這種方法只讀取第2,4,6行?方法如下。我的代碼有什麼問題?簡單的InputOutput方法

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; 
    } 

回答

5

您正在致電line = sr.ReadLine()兩次。

刪除此行,string str = sr.ReadLine();和使用可變line

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; 
}