使用C#消除CSV中的特殊字符

时间:2013-10-31 11:42:41

标签: c# visual-studio-2012 csv encoding asp.net-web-api

我使用此代码通过我的Web Api从CSV文件中获取数据

private List<Item> items = new List<Item>();

        public ItemRepository()
        {
            string filename = HttpRuntime.AppDomainAppPath + "App_Data\\items.csv";

            var lines = File.ReadAllLines(filename).Skip(1).ToList();

            for (int i = 0; i < lines.Count; i++)
            {
                var line = lines[i];

                var columns = line.Split('$');

                //get rid of newline characters in the middle of data lines
                while (columns.Length < 9)
                {
                    i += 1;
                    line = line.Replace("\n", " ") + lines[i];
                    columns = line.Split('$');
                }

                //Remove Starting and Trailing open quotes from fields
                columns = columns.Select(c => { if (string.IsNullOrEmpty(c) == false) { return c.Substring(1, c.Length - 2); } return string.Empty; }).ToArray();


                var temp = columns[5].Split('|', '>');
                items.Add(new Item()
                {
                    Id = int.Parse(columns[0]),
                    Name = temp[0],
                    Description = columns[2],

                    Photo = columns[7]



                });
            }
        }

但CSV文件返回的数据包含特殊字符而不是撇号。

例如,在CSV文件中,有诸如&#8217; s之类的值,应该是“有”或“约翰&#8217;”应该是“约翰”。 这&#8217;而不是撇号。

如何摆脱这个只是显示我的撇号。 这种数据正在返回  Name = temp[0], Description = columns[2],

1 个答案:

答案 0 :(得分:1)

您可以使用HttpUtility.HtmlDecode转换字符。这是一个例子:

var withEncodedChars = "For example in the CSV file the are values such as There&#8217;s which should be There's or John&#8217;s which should be John's. This &#8217; is there instead of an apostrophe.";

Console.WriteLine(HttpUtility.HtmlDecode(withEncodedChars));

如果您在控制台应用程序中运行它,则输出:

  

例如,在CSV文件中,有些值应该是,或者John应该是John的。这是'而不是撇号。

相关问题