1

I have an object in c# that needs to be saved as file and reused.

So basically what I am doing now is I am serializing a class to xml and I am saving it as a file. The file is aproximatelly 100MB.

Now the problem I am experiencing is when I want to deserialize file to class, I and up with OutOfMemoryException.

I am using the following code:

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(file);

Deserialize<T>(xmlDocument.InnerXml);

 public static T Deserialize<T>(string xmlContent)
 {
     var inStream = new StringReader(xmlContent);
     var ser = new XmlSerializer(typeof(T));
     return (T)ser.Deserialize(inStream);
 }
4
  • Why do you do xmlDocument.InnerXml, that seems odd. Commented Aug 6, 2015 at 13:59
  • If it's a really big file, you might experience an out of memory exception due to it being two times + overhead in your memory. Instead of reading the string (and thus storing it in memory) and then passing it to the Deserialize method, you could probably just pass a FileStream directly to your deserializer. Commented Aug 6, 2015 at 14:06
  • @Rosenheimer let me try you suggestion... Commented Aug 6, 2015 at 14:14
  • 1
    Just to clarify, you'll not use the XmlDocument at all. Commented Aug 6, 2015 at 14:15

1 Answer 1

2

Here's what my comment would look like in code:

    public static T Deserialize<T>(string Filepath)
    {
        using (FileStream FStream = new FileStream(Filepath, FileMode.Open))
        {
            var Deserializer = new XmlSerializer(typeof(T));
            return (T)Deserializer.Deserialize(FStream);
        }
    }
Sign up to request clarification or add additional context in comments.

3 Comments

this is what i just did. It solves the outofmemory issue. But in case anyone reads this question in the future, iis express will have a lot of outofmemoryexception which are resolved using iis.
"...which are resolved using iis." -Did you mean "...which are resolved using this."? If not, where are you getting additional exceptions?
your solution made it work on iis express. without your solution is does not work on iis express, but it works on iis. Optimizing memory usage is the key, but iis will tolerate more costly solutions then iis express. At the moment I also work on additional largers streams without saving them to files, so outofmemoryexception is such an often case with large files on iis express.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.