gpt4 book ai didi

c# - 解析具有动态列数的大型分隔文件

转载 作者:太空宇宙 更新时间:2023-11-03 11:48:28 25 4
gpt4 key购买 nike

如果在解析文件之前未知列,那么解析带分隔符的文件的最佳方法是什么?

文件格式为Rightmove v3 (.blm),结构如下:

#HEADER#
Version : 3
EOF : '^'
EOR : '~'
#DEFINITION#
AGENT_REF^ADDRESS_1^POSTCODE1^MEDIA_IMAGE_00~ // can be any number of columns
#DATA#
agent1^the address^the postcode^an image~
agent2^the address^the postcode^^~ // the records have to have the same number of columns as specified in the definition, however they can be empty
etc
#END#

文件可能非常大,我的示例文件是 40Mb,但也可能是几百兆字节。下面是我在意识到列是动态的之前开始使用的代码,我在阅读时打开文件流,这是处理大文件的最佳方式。我不确定将每条记录放入列表然后进行处理的想法有什么好处,不知道这是否适用于如此大的文件。

List<string> recordList = new List<string>();

try
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
StreamReader file = new StreamReader(fs);
string line;
while ((line = file.ReadLine()) != null)
{
string[] records = line.Split('~');

foreach (string item in records)
{
if (item != String.Empty)
{
recordList.Add(item);
}
}

}
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine(ex.Message);
}

foreach (string r in recordList)
{
Property property = new Property();

string[] fields = r.Split('^');

// can't do this as I don't know which field is the post code
property.PostCode = fields[2];
// etc

propertyList.Add(property);
}

关于如何做得更好的任何想法?如果有帮助,那就是 C# 3.0 和 .Net 3.5。

谢谢,

安妮

最佳答案

如果您可以去掉开头的一些行(标题内容和#xxx# 行),那么它只是一个以 ^ 作为分隔符的 csv 文件,因此任何 CSV reader class 都将做这个把戏。

关于c# - 解析具有动态列数的大型分隔文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2782563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com