【发布时间】:2023-09-16 15:19:01
【问题描述】:
我正在从DataGridView 写入一个 CSV 文件。
当我在这个过程中打开文件时(当任务正在写入文件时)我收到一个错误,因为:
The process cannot access the file 'xyz\filename.csv' because it is being used by another process.
我尝试在每次写入后在 file 和 swOut 上手动调用 Flush() 方法,但我仍然收到错误。
我需要使用FileMode.Append,因为在创建文件后我添加了 n 行。我已经尝试了 FileShare 枚举的每个不同选项,但没有任何效果。
我哪里错了?
我的代码:
using (FileStream file = new FileStream(output_file, FileMode.Append, FileAccess.Write, FileShare.Read))
{
StreamWriter swOut = new StreamWriter(file);
swOut.AutoFlush = true;
if (table.Rows.Count == 2)
{
for (int i = 0; i <= table.Columns.Count - 1; i++)
{
if (i > 0)
{
swOut.Write(",");
}
swOut.Write(table.Columns[i].HeaderText);
}
swOut.WriteLine();
}
swOut.Write(category.Replace(",", " ") + "," + name.Replace(",", " ") + "," + address.Replace(",", " ") + "," + locality.Replace(",", " ") + "," + cap.Replace(",", " ") + "," + tel.Replace(",", " ") + "," + fax.Replace(",", " ") + "," + www.Replace(",", " ") + "," + email_results.Replace(",", " ") + "," + business_url.Replace(",", " ") + "," + map_query.Replace(",", " "));
swOut.WriteLine();
file.Close();
if (stop == true) output_file = "";
}
【问题讨论】:
-
对不起,作为答案而不是评论发布。在右括号之前显示消息框。它显示了吗?
-
output_file也是在哪里声明的。你想通过if (stop == true) output_file = "";实现什么stop声明和设置在哪里? -
stop 是一个公共布尔值,当我单击停止 btn 时变为真。但是此时总是假的所以它不能什么都不做。
-
@Peuczyński 是的,它显示消息框。
标签: c# datagridview filestream streamwriter flush