Mohanapriya R Mohanapriya R
Updated date May 06, 2024
In this article, we will explore the simple process of converting strings to CSV in C#.

Convert Strings to CSV in C#

Below is a simple program that takes a list of strings and converts them into a CSV format:

using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        // Sample list of strings
        var stringList = new string[] { "John Doe", "25", "Software Developer" };

        // Convert strings to CSV
        string csvString = ConvertToCSV(stringList);

        // Display the CSV output
        Console.WriteLine("CSV Output:");
        Console.WriteLine(csvString);
    }

    static string ConvertToCSV(string[] values)
    {
        // Using StringBuilder for efficient string concatenation
        var csv = new StringBuilder();

        foreach (var value in values)
        {
            // Escape special characters if necessary
            string escapedValue = $"\"{value.Replace("\"", "\"\"")}\"";

            // Append the value followed by a comma
            csv.Append(escapedValue);
            csv.Append(",");
        }

        // Remove the trailing comma
        csv.Remove(csv.Length - 1, 1);

        return csv.ToString();
    }
}

The ConvertToCSV method takes an array of strings and converts them into a CSV-formatted string. Special characters, such as double quotes, are appropriately escaped, ensuring the integrity of the CSV format.

Output:

When you run the program, you'll see the following output:

CSV Output:
"John Doe","25","Software Developer"

Comments (0)

There are no comments. Be the first to comment!!!