1

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

3 Answers 3

4

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") ?

Sign up to request clarification or add additional context in comments.

1 Comment

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) :)
1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.