views:

372

answers:

4

Good morning all,

I'm having a few problems with a method in my C# code that should enable a DataGridView to be saved to a .txt file.

The code is as below:

private void saveToTxt_Btn_Click(object sender, EventArgs e)
    {
        filenameText.Text = serviceDataGrid.Rows.Count.ToString();
        //string toOutFile = @"C:\" + filenameText.Text+".txt";
        string toOutFile = @"C:\hello.txt";

        FileStream toFile = new FileStream(toOutFile, FileMode.Create);

        TextWriter toText = new StreamWriter(toOutFile);

        int count = serviceDataGrid.Rows.Count;

        toText.WriteLine("\t\t" + filenameText.Text);
        toText.WriteLine("\t\t" + directoryText.Text+"\n\n");

        for (int row = 0; row < count-1; row++)
        {
            toText.WriteLine(serviceDataGrid.Rows[row].Cells[0].Value.ToString());
        }
        toText.Close();
        toFile.Close();
    }

The following line is returning the error:

TextWriter toText = new StreamWriter(toOutFile);

IOException was unhandled. The process cannot access the file 'C:\hello.txt' because it is being used by another process.

I'm not entirely sure what the problem is, but it would suggest there are conflicts between FileStream and TextWriter.

Can anybody shed any light on this? Regards

+5  A: 

You are opening it twice; lose all the toFile stuff completely, and use using around toText:

    using(TextWriter toText = File.CreateText(toOutFile))
    {
        toText.WriteLine("\t\t" + filenameText.Text);
        toText.WriteLine("\t\t" + directoryText.Text+"\n\n");

        foreach(DataGridViewRow row in serviceDataGrid.Rows)
        {
            toText.WriteLine(row.Cells[0].Value.ToString());
        }
    }

Also; do you really mean WriteLine(... + "\n\n") ?

Marc Gravell
This works flawlessly. Thanks very much.WriteLine (.. + "\n\n"); did not behave as I imagined so I did mean it, but it didn't work (as I'm guessing you already knew) :)
Ric Coles
+1  A: 

When you are using line

TextWriter toText = new StreamWriter(toOutFile);

the following line is not required, because StreamWriter(string filePath) constructor will create a file if it does not exist.

FileStream toFile = new FileStream(toOutFile, FileMode.Create);

And Marc is right, you already have file open once in other instance variable, you cant open again.

Akash Kava
A: 

I've overseen that you open the writer with the filename. I thought you did TextWriter toText = new StreamWriter(toFile);

ManniAT
A: 

i want to display a text file to data grid by browsing and then loading it.

abhishek