Write a CSV file from an array in C#

[CSV file]

The example Read a CSV file into an array in C# shows how to load a CSV file into a two-dimensional array of strings. This example does the opposite: it saves a two-dimensional array of strings into a CSV (comma-separated value) file.

When you click the program’s Write button, the following code builds a two-dimensional array of data and uses it to write a CSV file.

// Write a CSV file.
private void btnWrite_Click(object sender, EventArgs e)
{
    // Create an array of data.
    // Note: The data must not contain commas.
    string[,] values =
    {
        { "WPF 3d-Three-Dimensional Graphics with WPF and C#", ... }, 
        { "The C# Helper Top 100-The 100 most popular posts at csharphelper.com", ... }, 
        { "Interview Puzzles Dissected-Solving and Understanding Interview Puzzles", ... }, 
        ...
    };

    // Convert the array into a CSV string.
    string csv = ArrayToCsv(values);

    // Write the CSV file.
    File.WriteAllText(txtFile.Text, csv);

    // Display the result.
    txtCsv.Text = File.ReadAllText(txtFile.Text);
}

This code first creates a two-dimensional array of strings. The values are wired into the code, but you could generate the values in whatever way suits your needs.

The code then calls the ArrayToCsv method (described shortly) to convert the array into a string with CSV format. It then simply calls File.WriteAllText to write that string into a CSV file. The code finishes by displaying the file’s contents in a text box so you can see what it looks like.

The following code shows how the ArrayToCsv method converts a two-dimensional array of string values into a single string with CSV format.

// Convert array data into CSV format.
private string ArrayToCsv(string[,] values)
{
    // Get the bounds.
    int num_rows = values.GetUpperBound(0) + 1;
    int num_cols = values.GetUpperBound(1) + 1;

    // Convert the array into a CSV string.
    StringBuilder sb = new StringBuilder();
    for (int row = 0; row < num_rows; row++)
    {
        // Add the first field in this row.
        sb.Append(values[row, 0]);

        // Add the other fields in this row separated by commas.
        for (int col = 1; col < num_cols; col++)
            sb.Append("," + values[row, col]);

        // Move to the next line.
        sb.AppendLine();
    }

    // Return the CSV format string.
    return sb.ToString();
}

The method first gets the array’s dimensions and then creates a StringBuilder to hold the final CSV string.

Next, the code loops through the array’s rows. For each row, it adds the row’s first value to the StringBuilder. It then loops through the rest of the fields in that row and adds them to the StringBuilder, separating them from the previous fields by commas.

After it has added all of a row’s fields to the StringBuilder, the code adds a new line.

After it has processed all of the array’s rows, the code converts the StringBuilder into a string and returns the result.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in database, files, strings and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *