We are currently engaged in a project where we need to export large volumes of data into a CSV file for our data science team. 

We need to export values such as "Ammy, IT, Paris France" where they should remain within a single column, with commas separating them into different fields. However, the issue arises when the address itself contains a comma, such as in "Paris, France", or special characters like `\r\n`, which might mistakenly be exported as separate rows in the CSV.

In this article, we will explore how to insert commas into a CSV string using C# to address this problem effectively.

we can solve that problem in a number of ways but the most generic method is to use double quote ” ” around the field, but it really depends on who is going to use your CSV files, we can delimit the commas, can change the commas to a special character or we can use a different delimiter, but the most common method is to use the “” around the values.

How to write a value which contain comma to a CSV file in c#?

In the below example, we are Writing Comma-separated values between double-quotes without space to generate CSV with a single column for comma-separated values.

Ex. I have three columns name, department & address With Values John HR & 24, Paris, France. so for creating CSV with given data, we need to generate the below line in our CSV.

name,department ,address  John,HR , "24, Paris, France"  

Code

public class Employee
    {
public string name
        {
get;
set;
        }
public string department
        {
get;
set;
        }
public string address
        {
get;
set;
        }
    }
    
public void CreateCsvFileWithComma()
        {
string csvFilePath = @"E:\MyJson\data.csv";
            List<Employee> employees = new List<Employee>();
            employees.Add(new Employee
            {
                name = "john",
                department = "HR",
                address = "24, place Delhi"
            });
            employees.Add(new Employee
            {
                name = "amit",
                department = "IT",
                address = "24, Janakpuri, Delhi"
            });
            StringWriter csv = new StringWriter();
            csv.WriteLine(string.Format("{0},{1},{2}", "Name", "Department", "adddress"));
foreach (var item in employees)
            {
                csv.WriteLine(string.Format("{0},{1},{2}", item.name, item.department, "\"" + item.address + "\""));
            }
            File.AppendAllText(csvFilePath, csv.ToString());
        }
    
Employee Class:

This class represents an employee with three properties: name, department, and address.

CreateCsvFileWithComma Method:


This method creates a CSV file containing information about employees.  It initializes a list of Employee objects and adds two instances with different details  then creates a StringWriter object named csv to help in constructing the CSV content.

Then function writes the CSV header with column names: "Name", "Department", and "address".
It iterates over each employee in the list and writes their information in CSV format using String.Format and separating each field with commas.

The address field is enclosed within double quotes to handle cases where the address itself contains commas, ensuring it's treated as a single entity.

Finally, it appends the CSV content to a file specified by csvFilePath,using above code we have implemented how to create a CSV file in C# with employee information, ensuring proper handling of comma-separated values, especially for fields that might contain commas within them.

You can also wirte a Helper Class for that
public class CSVWriter
{
        public void CreateCsvFileWithComma()
    {
        string csvFilePath = @"E:\MyJson\data.csv";
        List<Employee> employees = new List<Employee>();
        employees.Add(new Employee
        {
            name = "John",
            department = "HR",
            address = "24, Place, Delhi"
        });
        employees.Add(new Employee
        {
            name = "Amit",
            department = "IT",
            address = "24, Janakpuri, Delhi"
        });

        using (StreamWriter writer = new StreamWriter(csvFilePath))
        {
            writer.WriteLine("Name,Department,Address");

        foreach (var employee in employees)
            {
                writer.WriteLine($"\"{employee.name}\",\"{employee.department}\",\"{employee.address}\"");
            }
        }
    }
}
📰 Read more article

A CSV record, as the name suggests, ordinarily isolates data utilizing commas. It is an approach to trading organized data between programs, for example, the items in a calculation sheet, that may not be guaranteed to talk straightforwardly to one another.

However long the two projects can both open a CSV record, they can trade information. For instance, you can save contact data from Microsoft Excel as a CSV record, and import it into the Address Book in Microsoft Outlook.

The csv record design isn’t completely normalized. Isolating fields with commas is the establishment, yet commas or implanted line breaks in information must be taken care of exceptionally. A few executions deny such happy while others encompass the field with quotes, which makes the requirement for re-getting away in the event that quotes are available in the information.

The expression “CSV” likewise alludes to a few firmly related delimiter-isolated designs that utilization other field delimiters, for example, semicolons. These incorporate tab-isolated values and space-isolated values. A delimiter that is ensured not to be essential for the information enormously rearranges parsing.
Discretionary delimiter-isolated records are much of the time given the “.csv” expansion, notwithstanding the utilization of a non-comma field separator. This free phrasing can bring on some issues in information trade. Numerous applications that acknowledge CSV records have choices to choose the delimiter character and the statement character.