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();
您不在此代碼中定義'myLibraryBooks'。它可能是空的。 – Bobson 2013-02-25 16:47:17
或'books.Author'爲null – paul 2013-02-25 16:47:51
另外'TextReader.ReadToEnd()'不讀取一行 - 它讀取到文件末尾。 – 2013-02-25 16:49:01