prosseek
prosseek

Reputation: 190879

CA2000 StyleCop error message in processing XML string with XmlReader and StringReader

I use StringReader and XmlReader to process string that has XML code.

private static string GetData(string jobResultXml, string pipeName)
{
    StringBuilder result = new StringBuilder();
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ConformanceLevel = ConformanceLevel.Fragment;

    XmlReader reader = XmlReader.Create(new StringReader(jobResultXml), settings);

It compiles/builds fine, but when I run StyleCop, I got this error message.

Error   6   CA2000 : Microsoft.Reliability : In 
method 'ModelsimCommunicator.GetPipeData(string, string)', call System.IDisposable.Dispose 
on object 'new StringReader(jobResultXml)' before all references to it are out of scope.

What's needed for avoiding this StyleCop error message?

Upvotes: 0

Views: 483

Answers (1)

Steve Wilkes
Steve Wilkes

Reputation: 7135

Try:

private static string GetData(string jobResultXml, string pipeName)
{
    StringBuilder result = new StringBuilder();
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ConformanceLevel = ConformanceLevel.Fragment;

    using (StringReader stringReader = new StringReader(jobResultXml))
    using (XmlReader xmlReader = XmlReader.Create(stringReader, settings))
    {
    }

The StringReader is IDisposable so StyleCop wants you to dispose of it before it goes out of scope. The using() does that. Also while you're there, you might as well use a using() for the XmlReader, because that's IDisposable too :)

Upvotes: 2

Related Questions