Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing a .csv file - independent of the culture

Tags:

c#

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.

like image 716
Raghav55 Avatar asked Jun 29 '12 11:06

Raghav55


2 Answers

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!

like image 88
Vijay Avatar answered Sep 28 '22 05:09

Vijay


A quick solution so solve the German culture problem is to embed those double values with quotes. Results:

English: "10.5","20.3","30.2"
German: "10,5","20,3","30,2"

http://en.wikipedia.org/wiki/Comma-separated_values

like image 20
Dragomir Răzvan Avatar answered Sep 28 '22 06:09

Dragomir Răzvan