我有一个巨大的 .csv
文件,是具有2900万行的.TAB
文件,文件大小约为600 MB。我需要将其阅读到IEnumerable
集合中。
我尝试过CsvHelper
,GenericParser
和其他几个解决方案,但总是以不记忆力的例外
请建议一种做此操作的方法
我尝试了
var deliveryPoints = new List<Point>();
using (TextReader csvreader1 = File.OpenText(@"C:testfileProdPCDP1705.TAB")) //StreamReader csvreader1 = new StreamReader(@"C:testfileProdPCDP1705.TAB"))
using (var csvR1 = new CsvReader(csvreader1, csvconfig))
{
csvR1.Configuration.RegisterClassMap<DeliveryMap>();
deliveryPoints = csvR1.GetRecords<Point>().ToList();
}
using (GenericParser parser = new GenericParser())
{
parser.SetDataSource(@"C:testfileProdPCDP1705.TAB");
parser.ColumnDelimiter = 't';
parser.FirstRowHasHeader = false;
//parser.SkipStartingDataRows = 10;
//parser.MaxBufferSize = 4096;
//parser.MaxRows = 500;
parser.TextQualifier = '"';
while (parser.Read())
{
var address = new Point();
address.PostCodeID = int.Parse(parser[0]);
address.DPS = parser[1];
address.OrganisationFlag = parser[2];
deliveryPoints.Add(address);
}
}
和
var deliveryPoints = new List<Point>();
csvreader = new StreamReader(@"C:testfileProdPCDP1705.TAB");
csv = new CsvReader(csvreader, csvconfig);
while (csv.Read())
{
var address = new Point();
address.PostCodeID = int.Parse(csv.GetField(0));
address.DPS = csv.GetField(1);
deliveryPoints.Add(address);
}
问题是您将整个文件加载到内存中。您可以将代码编译到X64,这将迅速增加程序的内存限制,但是如果您避免将整个文件加载到内存中,则不建议使用。
请注意,调用Tolist((迫使CSVReader立即将整个文件加载到内存中:
csvR1.GetRecords<Point>().ToList();
,但一次只会加载一行:
foreach(var record in csvR1.GetRecords<Point>())
{
//do whatever with the single record
}
这样,您可以处理无限大小的文件
无需使用第三方软件。使用网库方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
StreamReader csvreader = new StreamReader(@"C:testfileProdPCDP1705.TAB");
string inputLine = "";
while ((inputLine = csvreader.ReadLine()) != null)
{
var address = new Point();
string[] csvArray = inputLine.Split(new char[] { ',' });
address.postCodeID = int.Parse(csvArray[0]);
address.DPS = csvArray[1];
Point.deliveryPoints.Add(address);
}
//add data to datatable
DataTable dt = new DataTable();
dt.Columns.Add("Post Code", typeof(int));
dt.Columns.Add("DPS", typeof(string));
foreach (Point point in Point.deliveryPoints)
{
dt.Rows.Add(new object[] { point.postCodeID, point.DPS });
}
}
}
public class Point
{
public static List<Point> deliveryPoints = new List<Point>();
public int postCodeID { get; set; }
public string DPS { get; set; }
}
}
它通过在x64模式下运行,并添加 <gcAllowVeryLargeObjects enabled="true" />
in app.config。