views:

81

answers:

1

I have the following method GetData that creates a StreamReader from a file.

private void GetData(string file)
{
    string filename = Path.GetFileNameWithoutExtension(file);
    XmlDocument xmldoc = new XmlDocument();

    using (StreamReader sr = new StreamReader(file))
    {
        Stream bs = sr.BaseStream;
        Stream cl = mainParser.CleanMarkup(bs);
        try
        {
            xmldoc = mainParser.LoadDocument(bs);
        }
        catch (XmlException ex)
        {
            // Exceptions are usually caused by non-compliant documents.
            // These errors are not critical to the operation of this program.
            Console.WriteLine(filename + " " + ex.Message);
        }
    }
    Msdn msdnParser = new Msdn(xmldoc);

    ListViewItem lvitem = new ListViewItem(filename);
    lvitem.SubItems.Add(filename);
    foreach (string item in msdnParser.Subitems)
    {
        lvitem.SubItems.Add(item);
    }
    listView.Items.Add(lvitem);
}

mainParser.LoadDocument(bs) calls the following:

public XmlDocument LoadDocument(Stream file)
{
    XmlDocument xmldoc = new XmlDocument();
    XmlReader xmlread = XmlReader.Create(file);
    xmldoc.Load(xmlread);

    return xmldoc;
}

StreamReader is disposed by GetData. Does this mean that I don't have to dispose of XmlReader since (I believe) this would dispose of its only unmanaged resource?

+1  A: 

The best "rule of thumb" to work by is, if something implements IDisposable, always wrap it in a using() block to ensure that any unmanaged resources it owns are disposed of correctly. Relying on the fact that the current implementation of "something" disposes of an underlying resource is dangerous and it won't hurt to wrap everythig in a using, just to be on the safe side =)

Rob
Ahh, this is a good point. This is probably a concept that I need to keep aware of. Always nice when an example shows up in my face.
Leonard Thieu