[英]How to Read from a Text File into a List And Read from that list C#
我需要从文本文件中读取,然后将每一行放入列表中,然后从该列表中读取。 但是我收到NullReferenceException“对象引用未设置为对象的实例。” 而一会儿大约下降了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的调试工具,逐行检查代码以查看问题出在哪里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.