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