Search code examples
c#file.readalllines

reading file to a list


i have a text file like this

a1,b1,30.04.2017
c1,d1,30.05.2017

i want to add every line to a list, the first two columns will be string variables s1 and s2 and the third one will be converted to a variable showing a date

i am not experienced at all and usually i find my answers searching here. i can only find examples reading lines containing the name of the variable and the value,

i think i will need to use the code below

 List<string> fileLines = new List<string>();

using (var reader = new StreamReader(fileName))
{
    string line;
    while ((line = r.ReadLine()) != null)
    {

    }
}

i cannot do the things inside the bracket, namely , parse the line , assign first column to variable s1 assign second column to variable s2 convert the third to date and assign it to d1 then add line to list

thanks in advance


Solution

  • In code below i write the parsed data, and you can use them how you want:

    List<string> fileLines = new List<string>();
    using (var reader = new StreamReader(fileName))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (line == "") continue; // refuse bare lines...
                    string a = line.Split(',')[0];
                    string b = line.Split(',')[1];
                    DateTime dt = DateTime.ParseExact(line.Split(',')[2], "dd.MM.yyyy", null);
                    fileLines.Add(line); // if you want....
                }
            }