【发布时间】:2016-05-25 04:17:28
【问题描述】:
我有一个 CSV 文件,但分隔符是分号 ;,每列都用双引号括起来。在& amp;等一些值中也会出现;
我正在使用 TextFieldParser 来解析文件。这是样本数据:
"A001";"RT:This is a tweet"; "http://www.whatever.com/test/module & amp;one"
对于上面的例子,我得到的列/字段比我应该得到的要多。
Field[0] = "A001"Field[1] = "RT:This is a tweet"Field[2] = "http://www.whatever.com/test/module&amp"Field[3] = "one"
这是我的代码。处理这种情况需要做哪些改变?
using (var parser = new TextFieldParser(fileName))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(";");
parser.TrimWhiteSpace = true;
parser.HasFieldsEnclosedInQuotes = false;
int rowIndex = 0;
PropertyInfo[] properties = typeof(TwitterData).GetProperties();
while (parser.PeekChars(1) != null)
{
var cleanFieldRowCells = parser.ReadFields().Select(
f => f.Trim(new[] { ' ', '"' }));
var twitter = new TwitterData();
int index = 0;
foreach (string c in cleanFieldRowCells)
{
string str = c;
if (properties[index].PropertyType == typeof(DateTime))
{
string twitterDateTemplate = "ddd MMM dd HH:mm:ss +ffff yyyy";
DateTime createdAt = DateTime.ParseExact(str, twitterDateTemplate, new System.Globalization.CultureInfo("en-AU"));
properties[index].SetValue(twitter, createdAt);
}
else
{
properties[index].SetValue(twitter, str);
}
index++;
}
}
-艾伦-
【问题讨论】:
-
您是否尝试将
HasFieldsEnclosedInQuotes设置为true? -
是的,但没有什么不同
-
尝试在每一行调用 System.Net.WebUtility.HtmlDecode()。它会将
&转换为“&”,并解码其他任何内容。 -
我确实有一种情况,数据看起来像“A001”;“RT:Test1;Test2”;“test.com”。以上是否也处理“Test1;Test2”?
-
System.Net.WebUtility.HtmlDecode()仅解码HTML。 IE。&、>等。它不会影响其他任何东西,所以像"A001";"RT: Test1 ; Test2";"test.com";这样的东西会被忽略。
标签: c# regex csv textfieldparser