writing a .csv file - independent of the culture

c#

Solution

You can probably get decimal separator and list separator from the current culture.

CultureInfo culture = new CultureInfo(currentCultureName);
string decimalSeparator = culture.NumberFormat.NumberDecimalSeparator;
string listSeparator = culture.TextInfo.ListSeparator;

And, if the value being written contains any of the separators then, enclose the value within double quotes.

string val = values[i].ToString(CultureInfo.InvariantCulture);
if(val.Contains(decimalSeparator) || val.Contains(listSeparator))
{
    val = string.Format("\"{0}\"", val);
}
m_StreamWriter.Write(val);
m_StreamWriter.Write(listSeparator);

Current culture name can be something like this: "en-US" for United States of America.

Hope this helps!

Problem

In German langauage- decimal seperators are , and value seperators are ";" . In English/other languages, decimal seperators are . and values seperators are ",". I want to create a .csv file indepedent of the current culture. I mean always the .csv file should have "." has decimal seperators and "," has value seperators. The code for this given below. ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Globalization; namespace CSV_FILE_FORMAT { class Program { static void Main(string[] args) { string aFileName = "result.csv"; FileStream aFileStream = new FileStream(aFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); StreamWriter m_StreamWriter = new StreamWriter(aFileStream); double[] values = new double[] { 10.5, 20.3, 30.2 }; for(int i = 0; i < values.Length;i++) { m_StreamWriter.Write(values[i].ToString(CultureInfo.InvariantCulture)); m_StreamWriter.Write(","); } } } } ``` The problem with this code is if OS is in German. The decimal seperators are shown "," instead of ".". Please let me know the code is missing something.

Original source