在CSV值C#周围加上引号

时间:2016-08-07 17:45:38

标签: c# csv

我有一个方法可以将制表符分隔的文本文件转换为CSV文件,并在包含逗号的字段周围添加引号。我想改变这种方法,因此它会在每个字段周围加上引号。

一个例子:

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

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

任何帮助将不胜感激。谢谢!

以下是我的代码:

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;
    }
}

2 个答案:

答案 0 :(得分:1)

    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;
        }

给定一个以逗号分隔的字符串,例如“乔治,华盛顿,是,a,总统”,这个函数会输出“George”,“Washington”,“was”,“a”,“president”

答案 1 :(得分:0)

简单明了

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

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

结果现在是:

  

&#34;乔治&#34;&#34;华盛顿&#34;&#34;是&#34;&#34;&#34;&#34;总统&#34;

str.Split convert分隔csv分隔的字符串,然后用","连接它们,在每个元素之间放置双引号,然后在结果的开头和结尾添加双引号。