DataGridView 写入文本文件 C# 时发生 IOException
大家早上好,
我的 C# 代码中的一个方法遇到了一些问题,该方法应该能够将 DataGridView 保存到 .txt 文件中。
代码如下:
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();
}
以下行返回错误:
TextWriter toText = new StreamWriter(toOutFile);
IOException 未处理。 该进程无法访问文件“C:\hello.txt”,因为它正在被另一个进程使用。
我不完全确定问题是什么,但它表明 FileStream 和 TextWriter 之间存在冲突。
有人能解释一下吗? 问候
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您打开它两次;完全丢失所有
toFile
内容,并在toText
周围使用using
:另外;您的意思是
WriteLine(... + "\n\n")
吗?You are opening it twice; lose all the
toFile
stuff completely, and useusing
aroundtoText
:Also; do you really mean
WriteLine(... + "\n\n")
?当您使用 line 时,
不需要以下行,因为 StreamWriter(string filePath) 构造函数将创建一个文件(如果它不存在)。
马克是对的,您已经在其他实例变量中打开了一次文件,您无法再次打开。
When you are using line
the following line is not required, because StreamWriter(string filePath) constructor will create a file if it does not exist.
And Marc is right, you already have file open once in other instance variable, you cant open again.
我已经监督您使用文件名打开编写器。
我以为你做到了
TextWriter toText = new StreamWriter(toFile);
I've overseen that you open the writer with the filename.
I thought you did
TextWriter toText = new StreamWriter(toFile);