1

I read through quite a few posts on SO regarding this and still need some help understanding this please.

CodeAnalysis is saying this method is disposing objects twice. Actually, it is warning me about this for two objects in the method; once for the file.InputStream and once for the reader object

Here is my code:

public void SaveCsvData(HttpPostedFileBase file, int vendorId)
        {
            var listCsvImport = new List<CsvImport>();

            try
            {
                using (var reader = new StreamReader(file.InputStream))
                using (var csvReader = new CsvHelper.CsvReader(reader))
                {

                    int count = 0;
                    while (csvReader.Read())
                    {
                        ...<snip>...

                        listCsvImport.Add(record);
                    }
                    _db.CsvImports.AddRange(listCsvImport);
                    _db.SaveChanges();
                }
...<snip>...

            }
            catch (CsvBadDataException ex)
            {
                log.Error("Invalid data in the CSV file, terminating process...");
                throw;
            }
            catch (Exception ex)
            {
                log.Error("Csv import failed, no data was saved.", ex);
                throw;
            }

        }

thanks

J Benjamin
  • 4,722
  • 6
  • 29
  • 39
  • Are you missing `{...}` for `using (var reader...`? – DavidG Oct 01 '14 at 10:11
  • 2
    This is probably caused by the fact that CsvReader, disposes of reader, so you don't need 2 using statements. This assumes that your actual code compile unlike the code you have posted. – Ben Robinson Oct 01 '14 at 10:14
  • @DavidG no sir, it is ok to stack using statements like that if you want to nest them. Nice thing is if something goes wrong they'll all dispose in the order they were instanted – J Benjamin Oct 02 '14 at 06:53
  • @JBenjamin Yes, you CAN do it, but it's generally recommended to NOT do it. – DavidG Oct 02 '14 at 08:06

1 Answers1

2

using (var csvReader = new CsvHelper.CsvReader(reader)) already disposes reader object, so you don't need to use using (var reader = new StreamReader(file.InputStream)).

Oğuz Sezer
  • 320
  • 3
  • 15
  • What makes you think that the first line disposes `reader`? – DavidG Oct 01 '14 at 10:16
  • 2
    @DavidG 'Do not dispose objects multiple times' warning, maybe? – Oğuz Sezer Oct 01 '14 at 10:18
  • 1
    Old question/answer, I know. But the following GitHub issue confirms the behaviour where CsvReader disposes the passed in StreamReader https://github.com/JoshClose/CsvHelper/issues/396 (Personally I would dispose the StreamReader rather than the CsvReader, unless instantiating both at the same time.) – Quails4Eva Feb 08 '16 at 16:41