0

I have some code that saves data from a class to .csv files, but I am not sure how to read it back into a class so I can put it in a listview. Here is the code for the save:

        SaveFileDialog save = new SaveFileDialog();
        save.Filter = "Excel|*.csv";

        if (save.ShowDialog() == DialogResult.OK)
        {
            StreamWriter sw = new StreamWriter(save.FileName);
            try
            {
                sw.WriteLine("Name" + ";" + "Authors" + ";" + "Pages" + ";" + "Date" + ";" + "Price" + ";" + "Copies");
                foreach (Book b in bookList)
                {
                    string aux = "";
                    aux = string.Join(";", b.Authors);//I know I will probably need to change ';' here because it will have trouble reading it
                    sw.WriteLine(b.Name + ";" + aux + ";" + b.Pages + ";" + b.Date.ToString("dd.MM.yyyy") + ";" + b.Price + ";" + b.Copies);
                }
            }
            catch (IOException ert)
            {
                MessageBox.Show(ert.Message);
            }
            catch (Exception ew)
            {
                MessageBox.Show(ew.Message);
            }
            finally
            {
                sw.Close();
            }
        }
svick
  • 236,525
  • 50
  • 385
  • 514
Xzya
  • 337
  • 7
  • 16

2 Answers2

2

This is actually pretty easy. Lets assume you have the following class Book:

public class Book
{
    public string Name { get; set; }
    public int Pages { get; set; }
    public string AuthorName { get; set; }
}

Then you can simple read it like this:

var BooksFromCsv = from row in File.ReadLines(@"C:\books.csv").Where(arg => !string.IsNullOrWhiteSpace(arg) && arg.Length > 0).AsEnumerable()
                   let column = row.Split(';')
                   select new Book
                   {
                      Name = column[0],
                      Pages = column[1],
                      AuthorName = column[2],
                   };

The Result will be an IEnumerable<Book>. If you want a List or an Array just append an .ToList() or .ToArray().

Marco
  • 22,856
  • 9
  • 75
  • 124
  • There are so many things that can go wrong with a naive split. If you know that your text won't contain the delimiter, this works fine. But the first time somebody puts a semicolon in a quoted string, this turns into a nightmare. – Jim Mischel Mar 19 '14 at 22:24
  • Would this work if header are also included in the file? – vishwas-trivedi Jul 26 '19 at 01:49
  • Should be possible. Only thing to add is a Skip call to skip the first line. – Marco Jul 26 '19 at 06:05
0

If you only want to save your data persistent you could serialise and deserialise your object like this:

// SAVE

using (var fs = new FileStream(path, FileMode.Create))
{
      var xSer = new XmlSerializer(typeof(objecttype));
      xSer.Serialize(fs, myObject);
}

// LOAD

using (var fs = new FileStream(path, FileMode.Open))
{
     var xSer = new XmlSerializer(typeof(objecttype));
     myObject = (objecttype)xSer.Deserialize(fs);
}
aDoubleSo
  • 1,128
  • 9
  • 19