如何从文本文件读取到列表并从列表中读取
本文关键字:读取 列表 文件 文本 | 更新日期: 2023-09-27 18:01:15
我需要从文本文件中读取,然后将每行放入列表中,然后从该列表中读取。但我得到一个NullReferenceException"对象引用不设置为对象的实例。"在while异常中大约向下7行。我已经把我能想到的都试过了。提前谢谢。
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();
您正在声明books
,但它看起来不像是被设置为任何东西(除非您在构造函数中做了一些奇怪的事情)。基于此,我要说下面这行可能会导致这个异常:
*Guessing Author is null...
books.Author.ToUpper()
利用。net的调试工具,逐行检查代码,看看问题出在哪里。