This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

C# Programming
.NET 1.1+

Convert String Arrays to Comma-Separated Strings

Integrating with legacy systems often includes sending lists of string values in a comma-separated format. If you are holding the values in an array of strings, you can use a method of the String class to automatically generate the delimited list.

Comma-Separated Files

Many systems provide the ability to import information from comma-separated value (CSV) files. These simple, small files of textual data are less sophisticated that modern databases and XML. However, they are often used by legacy systems for which the C# programmer must develop integration software.

When generating CSV information it is common to begin with an array of strings or a collection that can be converted into such an array. Each element of the array will contain a single string that needs to be entered into the comma-separated file. The conversion is easy to achieve in C# and the .NET framework using the Join method of the String class.

String.Join Method

The static Join method requires two parameters. The first parameter holds a string containing the delimiter that will be placed between each item from the array. The second parameter is the array of strings to be joined. The method returns a string containing the joined items.

The following code shows the Join method in action:

string[] vegetables = new string[] { "Artichoke", "Bean", "Cabbage", "Carrot" };
string joined = String.Join(", ", vegetables);

Console.WriteLine(joined);  // Outputs "Artichoke, Bean, Cabbage, Carrot"
1 March 2008