Parsing semi colon delimeter file

一笑奈何 提交于 2019-12-05 23:25:26

Using the two sample strings you have above and setting the HasFieldsEnclosedInQuotes property to true works for me.

string LINES = @"
    ""A001"";""RT:This is a tweet""; ""http://www.whatever.com/test/module&one""
    ""A001"";""RT: Test1 ; Test2"";""test.com"";   
";
using (var sr = new StringReader(LINES))
{
    using (var parser = new TextFieldParser(sr))
    {
        parser.TextFieldType = FieldType.Delimited;
        parser.SetDelimiters(";");
        parser.TrimWhiteSpace = true;
        parser.HasFieldsEnclosedInQuotes = true;

        while (parser.PeekChars(1) != null)
        {
            var cleanFieldRowCells = parser.ReadFields().Select(
                f => f.Trim(new[] { ' ', '"' })).ToArray();
            Console.WriteLine("New Line");
            for (int i = 0; i < cleanFieldRowCells.Length; ++i)
            {
                Console.WriteLine(
                    "Field[{0}] = [{1}]", i, cleanFieldRowCells[i]
                );
            }
            Console.WriteLine("{0}", new string('=', 40));
        }
    }
}

OUTPUT:

New Line
Field[0] = [A001]
Field[1] = [RT:This is a tweet]
Field[2] = [http://www.whatever.com/test/module&amp;one]
========================================
New Line
Field[0] = [A001]
Field[1] = [RT: Test1 ; Test2]
Field[2] = [test.com]
Field[3] = []
========================================
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!