I'm trying to read from a text file in C# and assign each line to specific variables but I get Unhandled Exception: System.ArgumentNullException: Value cannot be null. Error when I try to convert string to SongGenre.
public static void LoadSongs(string fileName)
{
string title = "a";
string artist;
string length;
string genre;
TextReader reader = new StreamReader(fileName);
while (title != null)
{
title = reader.ReadLine();
artist = reader.ReadLine();
length = reader.ReadLine();
genre = reader.ReadLine();
songs.Add(new Song(title,
artist,
Convert.ToDouble(length),
(SongGenre)Enum.Parse(typeof(SongGenre),
genre)));
}
reader.Close();
}
file name refers to a text file which is ok. I tried to it outside a loop like this:
TextReader reader = new StreamReader(fileName);
string title = reader.ReadLine();
string artist = reader.ReadLine();
double length = Convert.ToDouble(reader.ReadLine());
SongGenre genre = (SongGenre)Enum.Parse(typeof(SongGenre),
reader.ReadLine());
songs.Add(new Song(title, artist, length, genre));
string title1 = reader.ReadLine();
string artist1 = reader.ReadLine();
double length1 = Convert.ToDouble(reader.ReadLine());
SongGenre genre1 = (SongGenre)Enum.Parse(typeof(SongGenre),
reader.ReadLine());
songs.Add(new Song(title1, artist1, length1, genre1));
and it worked. I also tried to print genre using Console.WriteLine and it was working so I made sure that it is no null but I don't know why am I receiving this error.
It is not a duplicate of other questions. The loop is not working correctly and below you can find how to fix it.