1

I am getting data from a CSV file through my Web Api with this code

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]



                });
            }
        }

But the CSV file returned data with special characters instead of an apostrophe.

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.

How do I get rid of this to just show my apostrophe. This kind of data is being returned in Name = temp[0], Description = columns[2],

4

1 回答 1

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 文件中的值是 There's 应该是 There's 或 John's 应该是 John's。这个 ' 在那里而不是撇号。

于 2013-10-31T12:19:16.673 回答