0

Our application requires logging API requests and we are logging them in the XML format in our file system. But we're getting an Index out of range error from time to time and are unable to reproduce them locally.

On checking the Stack trace we were able to identify that the error originates from our XML serializer method that converts an object to an XML string.

I'm using the following method to serialize objects to an XML string

public static string Serialize(object input)
{
    string output = "";
    var serializer = new XmlSerializer(input.GetType());
    
    using (var writer = new StringWriter())
    {
        serializer.Serialize(writer, input);
        output = writer.ToString();
    }

    return output;
}

But we are seeing the following error from time to time

Error occurred - Index was out of range. 
Must be non-negative and less than the size of the collection. Parameter name: chunkLength

When searching the above error I found out that the StringBuilder throws this because it doesn't support multithreading. (link to post here)

I want to know if using the StringWriter is causing this and if so, what should I use inplace of it so that I stop getting this error?

Thanks in advance

  • I wonder if it happens during the Serialize process at the call to [`WriteNode`](https://referencesource.microsoft.com/System.Xml/R/de75010c27d4513b.html), when it calls: `this.WriteChars(writeNodeBuffer, 0, read)`? I suppose you could try adding a `try/catch(IndexOutOfRangeException)` around that code and logging the details of the object being serialized. Do you have the line number for the exception? – Rufus L Feb 03 '23 at 19:56

0 Answers0