user3430861 user3430861 - 2 months ago 17
C# Question

Creating CSV File from string array

I am trying to export data from a list of object to a csv file. I managed to create the file and create the first row, however I need to create some kind of for each loop to loop through each object.

This is my code:

string pathDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filePath = pathDesktop + "\\mycsvfile.csv";

if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}

string delimter = ",";
string[][] output = new string[][] {
new string[] {"TEST1","TEST2"}
};

int length = output.GetLength(0);
StringBuilder sb = new StringBuilder();

for (int index = 0; index < length; index++)
{
sb.AppendLine(string.Join(delimter, output[index]));
File.AppendAllText(filePath, sb.ToString());
}


Is there any way to create this file and using a loop to loop through all my objects and display them in file.

Answer

Here's the solution:

string pathDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filePath = pathDesktop + "\\mycsvfile.csv";

if (!File.Exists(filePath))
{
    File.Create(filePath).Close();
}
string delimter = ",";
List<string[]> output = new List<string[]>();

//flexible part ... add as many object as you want based on your app logic
output.Add(new string[] {"TEST1","TEST2"});
output.Add(new string[] {"TEST3","TEST4"});

int length = output.Count;

using (System.IO.TextWriter writer = File.CreateText(filePath))
{
    for (int index = 0; index < length; index++)
    {
        writer.WriteLine(string.Join(delimter, output[index]));
    }
}