0

I am currently using this code to save the data in .txt file. How should I create a csv file instead with proper heading in every column?

private string _path = "review.txt";
public static void WriteToTextFile(string path, string data, bool append = true, int count = 1)
        {
            if (!File.Exists(path))
            {
                var file = File.Create(path);
                file.Close();
            }
            using (StreamWriter writer = new StreamWriter(path, append: append))
            {
                if (!append)
                {
                    //remove opening bracket "[" from data passed
                    data = data.Trim().Substring(1, data.Trim().Length - 1);
                    //remove last bracket "]" from data passed
                    data = data.Trim().Substring(0, data.Trim().Length - 1);
                }
                if (count != 0)
                {
                    data = data + ",";
                }
                writer.WriteLine(data);
            }
        }
        public string SaveReview(Review data)
        {
            string str = JsonConvert.SerializeObject(data, Formatting.None);
            Utility.WriteToTextFile(_path, str);
            return "success";
        }

  • Also: https://stackoverflow.com/questions/3532162/create-a-csv-file-in-c-sharp & https://github.com/jitbit/CsvExport –  Dec 01 '20 at 14:17

1 Answers1

1

Usually if you want to write data to a CSV-file, you have a sequence of similar objects, where you want to write most properties. One object per row, all properties of the same object on the same row. Optionally you want to write a header.

Nuget Package CSVHelper is your partner.

class Student
{
    public int Id {get; set;}
    public string Name {get; set;}
    public DateTime BirthDay {get; set;}
    ...
}

public ICollection<Student> GetStudents() {...}

public void SaveStudents(string fileName, ICollection<Student> students)
{
    using (var textWriter = File.CreateText(fileName))
    {
        using (var csvWriter = new CsvWriter(textWriter))
        {
            // if you want a Header
            csvWriter.Configuration.HasHeaderRecord = true;
            csvWriter.WriteRecords(students);
        }
    }
}

There are a lot of possibilities to omit writing some properties, or format the written data, etc.

Reading is as simple as writing. Be careful though: the more decoration you do on writing, the more decoration you must remove when reading.

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116