C# : System.OutOfMemoryException while reading large XML file

Hegde, Deepak 0 Reputation points
2023-06-02T02:04:37.46+00:00

System.OutOfMemoryException

I have an xml file which is about 50MB and I am trying to read the content using the below snippet in C#:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"c:\temp\myfile.xml");

I received the below exception few times. Can you comment if the exception is due to the size of the file (if there is a limit to the file size) or could be due to the system resources ? I assume this API is used by lot of developers so the exception should be seen by a lot of them if it is related to file size.

System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
   at System.Xml.XmlElement.get_Attributes()
   at System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace)
   at System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc)
   at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
   at System.Xml.XmlDocument.Load(XmlReader reader)
   at System.Xml.XmlDocument.Load(String filename)
Developer technologies | C#
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.