I want to read records from XML files and save the data to another file or database. The data I am interested in is actually very small but I often run into an "out of memory" exception. The problem I see is the XML files because some are very large (several gigabytes) and they contain countless records. I don't need all these records at the same time. Whenever I have read a certain number, I save them and discard my read data.
The code to load this data looks like this for me:
using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader reader = new StreamReader(bs))
{
string line;
while ((line = reader.ReadLine()) != null)
{
using (XmlReader xr = XmlReader.Create(reader))
{
while (xr.Read())
{
switch (xr.NodeType)
{
case XmlNodeType.Element:
if (xr.LocalName == "Record")
{
string xml = xr.ReadOuterXml();
// Parse XML, Put data into list, save list and clear list
It works fine on smaller files but maybe it is not the best practice for reading very big files.
All suggestions will be gratefully received.