2013-02-25 89 views
0

我需要從文本文件讀取,然後將每行放入列表中,然後從列表中讀取。但是我得到一個NullReferenceException「對象引用未設置爲對象的實例。」在同時例外的情況下,約有7條線。我試過了我能想到的一切。提前致謝。如何從文本文件讀取到列表中並從該列表中讀取C#

   StreamReader sre = new StreamReader(FILE_PATH); 
       Books books = new Books(); 
       string line; 
       while ((line = sre.ReadToEnd()) != null) 
       { 
       //NullReferenceException is Right here 
       //I defined myLibraryBooks outside of this code; But it is in the same scope 
        myLibraryBooks.Add(new Books() { Author = books.Author.ToUpper(), Title = line.ToUpper(), ISBN = line, Publish_Date = line }); 
       } 
       Console.Write("Enter Author's Name:"); 
       string input_to_find = Console.ReadLine(); 
       var author = from Authors in myLibraryBooks 
          where Authors.Author == input_to_find 
          select Authors; 

       foreach (var book in author) 
       { 
        Console.WriteLine(String.Format("  Author   Title   ISBN   Publish Date")); 
        Console.WriteLine(String.Format("  {0}   {1}    {2}    {3}", books.Author, books.Title, books.ISBN, books.Publish_Date)); 
       } 
       sre.Dispose(); 
+2

您不在此代碼中定義'myLibraryBooks'。它可能是空的。 – Bobson 2013-02-25 16:47:17

+2

或'books.Author'爲null – paul 2013-02-25 16:47:51

+1

另外'TextReader.ReadToEnd()'不讀取一行 - 它讀取到文件末尾。 – 2013-02-25 16:49:01

回答

1

您聲明books,但它並不像它是越來越設置爲任何(除非你是在構造函數做一些怪異的東西)。在此基礎上,我會說下面的線路可能會導致此異常:

 *Guessing Author is null... 
books.Author.ToUpper() 

採取的.NET的調試工具的優勢,並通過線通過您的代碼行步,看看問題出在哪裏。