0

I am using LinqToCSV to export list of values in C#, and it works fine when I use only two lines as

        LINQtoCSV.CsvContext CSVContext = new CsvContext();
        CSVContext.Write(bullishRowList, "C://FileName.CSV");

But I want to use SaveFileDialog to allow user to choose the location where he wants to save the file. I did the following for this purpose. I took this code from here

        Stream myStream;
        SaveFileDialog saveFileDialog1 = new SaveFileDialog();

        saveFileDialog1.Filter = "csv files (*.csv)|*.csv";
        saveFileDialog1.FilterIndex = 2;
        saveFileDialog1.RestoreDirectory = true;

        if (saveFileDialog1.ShowDialog() == DialogResult.OK)
        {
            if ((myStream = saveFileDialog1.OpenFile()) != null)
            {
                LINQtoCSV.CsvContext CSVContext = new CsvContext();
                CSVContext.Write(bullishRowList, saveFileDialog1.FileName);
                myStream.Close();
            }
        }

It gives an error "The process cannot access the file 'C:\aaa' because it is being used by another process" on line CSVContext.Write(bullishRowList, saveFileDialog1.FileName); I can't figure out what is the problem with this piece of code. please help me.

Lali
  • 2,816
  • 4
  • 30
  • 47

1 Answers1

1

It is your own process that opens the file in this line

    if ((myStream = saveFileDialog1.OpenFile()) != null)

and that line is not necessary

    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        if (saveFileDialog1.FileName != string.Empty)
        {
            LINQtoCSV.CsvContext CSVContext = new CsvContext();
            CSVContext.Write(bullishRowList, saveFileDialog1.FileName);
        }
    }

I have never used that library, but looking briefly at their documentation, if you want to open yourself the stream, then you need to pass the opened stream to the Write method

    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        if ((myStream = saveFileDialog1.OpenFile()) != null)
        {
            LINQtoCSV.CsvContext CSVContext = new CsvContext();
            CSVContext.Write(bullishRowList, myStream);
            myStream.Close();
        }
    }
Steve
  • 213,761
  • 22
  • 232
  • 286