'Type used in a using statement should be implicitly convertible to IDisposable

I have the following logic:

try
{
   using (var contents = new StreamReader(file.InputStream).ReadToEnd()) 
   {
       var rows = contents.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
       rows.ForEach(r => mids.Add(r.Split(',')[0]));
   }
}
catch(IOException e)
{}
finally
{
   contents = null;
}

In the using statement I have an error in the question. It happened probably because I use .ReadToEnd() method.

Without the using statement I would need to use try/catch/finally for a clean up (to fix veracode resource clean up issue)

How can I fix that, so I don't need to use try\catch\finally and use only the using statement?



Solution 1:[1]

So, using should be used with object which implements IDisposable interface. You calling ReadToEnd method which returns string and contents is not a IDisposable (because string is not). You should use it like this:

using (var streamReader = new StreamReader(file.InputStream)) 
{
    var contents = streamReader.ReadToEnd();
    // Some actions
}

You want to clean up StreamReader, contents will be collected by GC when method will finished because it has type string.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sergey Nazarov