Saving to File with much data creates OutOfMemoryException

Jul 29, 2013 at 3:26 PM
As for the saving to a file strings are used, the memory can be get very big if you use much data. Example from an ongoing project are 12500 customer and 595000 vouchers plus one section for extraction information. With the actual version and the usage of string the memory usage will go up to nearly 3.5 GB. Depending on the machine this can cause the Exception "OutOfMemory".
As with even more Data the memory usage will be greater than in the above example and so most machines will raise the Exception.

There is a solution to reduce the amount of memory which is used. Instead of using Strings by StreamReader.ReadToEnd() the XML-Object can be directly serialized into a file. Following code can be used:
        System.IO.FileStream fileStream = null;
            fileStream = new FileStream(fileName, FileMode.Create);
            Serializer.Serialize(fileStream, this);
            if ((fileStream != null))
Now the memory amount is reduce to 1/6 of before.