我有一个小程序,它读取一个CSV文件,其中包含一个用逗号分隔的报告。在报告中,其中一个字段是日期,我将其转换为日期/时间,并且仅提取来自特定时间范围内的信息。这是我的问题:报告实际上是在某个系统上运行的作业列表。但是,有些作业名称自己包含逗号。这意味着Excel输出报告非常混乱,因为如果作业名称具有逗号,则作业名称将在2个单元格之间划分。我对编程有点新意,所以我想到解决这个问题的唯一方法是检查我的数组中有多少字段以逗号分隔。如果它大于正常值,我会连接两个我知道将成为工作名称的字段。但是,问题在于,如果作业名称包含2个逗号,则这将不起作用,因为它仅设置为处理数据中的1个额外逗号。
我应该补充一点,我读到的CSV报告是由另一个应用程序生成的,我无法控制它的分隔方式。否则,我会将其更改为管道或类似的东西。
有什么想法?以下是处理它的代码部分:
StreamReader SR = new StreamReader(inputFile);
StreamWriter SW = new StreamWriter(outputFile);
string records;
//read headers from first line
string headers = records = SR.ReadLine();
SW.WriteLine(headers);
DateTime YesterdayAM = Convert.ToDateTime(DateTime.Now.AddDays(-1).ToShortDateString() + " 05:00:00 AM");
while ((records = SR.ReadLine()) != null)
{
if (records.Trim().Length > 0)
{
string daterecord = GetDateTimeFromStringArray(records);
if (daterecord.Length > 0)
{
DateTime recordDate = Convert.ToDateTime(daterecord);
if (recordDate >= YesterdayAM)
{
string[] checkfields = records.Split(',');
if (checkfields.Length > 13)
{
string[] replacefields = { checkfields[0], checkfields[1] + " " + checkfields[2], checkfields[3], checkfields[4], checkfields[5], checkfields[6], checkfields[7], checkfields[8], checkfields[9], checkfields[10], checkfields[11], checkfields[12] };
for (int i = 0; i < replacefields.Length; i++)
{
SW.Write(replacefields[i] + ",");
}
SW.Write(Environment.NewLine);
}
else
{
SW.WriteLine(records);
}
}
}
}
}
答案 0 :(得分:0)
以这种方式做这件事有点蠢,但如果你无法修复源代码并且知道那么额外的逗号只会出现在你可以做的一个字段中像这样的东西:
string[] checkfields = records.Split(',');
while (checkfields.Length > 13)
{
// concat [1] & [2] into a new array
checkfields = checkfields.Take(1)
.Concat(new string[] { string.Join("", checkfields.Skip(1).Take(2).ToArray()) })
.Concat(checkfields.Skip(3)).ToArray();
} // if it's still too long it will loop again
或者更好:
string[] checkfields = records.Split(',');
int extraFields = checkfields.Length - 13;
if (extraFields > 0)
{
// concat fields 1....1 + extraFields
checkfields = checkfields.Take(1)
.Concat(new string[] { string.Join("", checkfields.Skip(1).Take(extraFields).ToArray()) })
.Concat(checkfields.Skip(extraFields + 1)).ToArray();
} // avoids looping by doing it all in one go
注意:linq语句未经测试,可能不是绝对最有效的方法。还有所有&#34;魔法&#34;数字应该可以用常量替换以保持可维护性。