Skip to content

Resource leak: StringWriter not disposed in ServiceExporter.ExportXml #95

@Christophe-Rogiers

Description

@Christophe-Rogiers

Bug Description

StringWriter in ExportXml() is created but never disposed. Additionally, ExportJson() has a redundant .ToString() call on the return value of JsonConvert.SerializeObject(), which already returns a string.

Actual Behavior

// ServiceExporter.cs lines 16-21
public static string ExportXml(ServiceDto service)
{
    var xml = new StringWriter();
    new System.Xml.Serialization.XmlSerializer(typeof(ServiceDto)).Serialize(xml, service);
    return xml.ToString();
}

// ServiceExporter.cs lines 38-46
public static string ExportJson(ServiceDto service)
{
    var json = JsonConvert.SerializeObject(service, Formatting.Indented,
        new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore
        });
    return json.ToString(); // redundant .ToString()
}

Suggested Fix

public static string ExportXml(ServiceDto service)
{
    using var xml = new StringWriter();
    new System.Xml.Serialization.XmlSerializer(typeof(ServiceDto)).Serialize(xml, service);
    return xml.ToString();
}

public static string ExportJson(ServiceDto service)
{
    return JsonConvert.SerializeObject(service, Formatting.Indented,
        new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore
        });
}

Environment

  • File: src/Servy.Core/Services/ServiceExporter.cs
  • Lines: 16-21 (ExportXml), 38-46 (ExportJson)

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions