YoungStamos
YoungStamos

Reputation: 101

Put quotes around CSV values C#

I have a method that converts a tab delimited text file to a CSV file and it puts quotes around fields that have a comma in it. I want to alter this method so it puts quotes around every field.

An example:

Convert (George, Washington,was,a,president)

to

("George","Washington","was","a","president").

Any help would be appreciated. Thank you!

Below is my code:

public void ConvertToCSV()
    {
        //converts a tab delimited text file to a csv file
        string textFilePath = @"C:\Reports\file.txt";

        string csvFilePath = @"C:\Reports\file.csv";


        var input = File.ReadAllLines(textFilePath);
        var lines = input.Select(row => row.Split('\t'));
        lines = lines.Select(row => row.Select(field => field.EscapeCsvField(',', '"')).ToArray());
        var csv = lines.Select(row => string.Join(",", row));
        File.WriteAllLines(csvFilePath, csv.ToArray());

        System.IO.File.Delete(textFilePath);

    }

static class Extension
{
    public static String EscapeCsvField(this String source, Char delimiter, Char escapeChar)
    {
        if (source.Contains(delimiter) || source.Contains(escapeChar))
            return String.Format("{0}{1}{0}", escapeChar, source);

        return source;
    }
}

Upvotes: 2

Views: 5005

Answers (2)

Marco Scabbiolo
Marco Scabbiolo

Reputation: 7469

Plain and simple

var str = "George, Washington,was,a,president";

var result = "\"" + string.Join("\",\"", str.Split(',')) + "\"";

Result is now:

"George","Washington","was","a","president"

str.Split converts separates the csv delimited strings, then you join them with "," to put double quotes between every element, and then add double quoptes to the start and the end of the result.

Upvotes: 0

itzJustKranker
itzJustKranker

Reputation: 63

    private string convertCSV(string pCSVtext)
    {
        string returnText = "";
        pCSVtext = pCSVtext.Replace(" ", "");
        string[] split = pCSVtext.Split(Convert.ToChar(","));
        for (int i = 0; i < split.Length; i++)
        {
            returnText += "\"" + split[i].ToString() + "\"";

            if(i != split.Length - 1)
            {
                returnText += ",";
            }

        }
        return returnText;
    }

string[] csvVals = new string[5] { "George", "Washington", "Was", "A", "President" };

        public string convertCSV_Array(Array pCSVvals)
        {
            string returnString = "";
            int i = 0;
            foreach(string val in pCSVvals)
            {
                returnString += "\"" + val + "\"";
                if (i != pCSVvals.Length - 1)
                {
                    returnString += ",";
                }
                i++;
            }
            return returnString;
        }

Given a comma delimited string such as the example, "George,Washington,was,a,president" this function would output "George","Washington","was","a","president"

Upvotes: 1

Related Questions