Kyson Gardner
Kyson Gardner

Reputation: 9

How to Read from a Text File into a List And Read from that list C#

I need to Read from a Text File and then put each line into a list then read from that list. But I am getting a NullReferenceException "Object reference not set to an instance of an object." In the while exception about 7 lines down. I have tried out everything I can think of. Thanks in advance.

                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();

Upvotes: 0

Views: 443

Answers (1)

Abe Miessler
Abe Miessler

Reputation: 85056

You are declaring books, but it doesn't look like it is getting set to anything (unless you are doing some weird stuff in your constructor). Based on this, I would say the following line could cause this exception:

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

Take advantage of .NET's debugging tools and step through your code line by line to see where the problem is.

Upvotes: 1

Related Questions