I am working with StringWriter , which I pass to the method of writing values ββin a foreach . I believe this causes two warnings to be generated:
CA2000: Microsoft.Relability: in the ToCsvService.ToCsv () method, the "sw" object is not located on all exception paths. Call System.IDisposable.Dispose on the 'sw' object before all references to it go out of scope.
and
CA2202: Microsoft.Usage: Object 'sw' can be deleted more than once in the ToCsvService.ToCsv () method. To avoid throwing a System.ObjectDisposedException, you should not throw Dispose more than once on an object.
public string ToCsv() { IEnumerable<string> props = GetProperties(); StringWriter sw = new StringWriter();
I forgot GetProperties() from the list of methods invoked, as it did not seem appropriate.
private string GetHeadings(IEnumerable<string> props) { string headings = String.Join(",", props.Select(prop => _headings.ContainsKey(prop) ? _headings[prop] : prop)); return headings; } private void WriteValues(IEnumerable<string> props, StringWriter sw) { foreach (object obj in _collection) { var x = obj.GetType().GetProperties() .Where(pi => props.Contains(pi.Name)) .Select(pi => _format.ContainsKey(pi.Name) ? String.Format("{0:" + _format[pi.Name] + "}", pi.GetGetMethod().Invoke(obj, null)) : pi.GetGetMethod().Invoke(obj, null).ToString()); string values = String.Join<string>(",", x); sw.WriteLine(values); } }
Why are these warnings generated?
source share