【发布时间】:2018-01-30 16:52:18
【问题描述】:
我在下面包含的代码已成功写入 CSV 文件。但是,如果我正在写入的 CSV 文件恰好在 Excel 中打开,我会收到一个 System.IO.Exception,表示“该文件正在被另一个进程使用。”
如何更改我的代码以使程序继续运行并等到 CSV 不再在 Excel 中打开?
private void timer1_Tick(object sender, EventArgs e)
{
int actmonth, actyear, actsecond;
System.DateTime fecha = System.DateTime.Now;
actmonth = fecha.Month;
actyear = fecha.Year;
if (actmonth <= 9)
{
valorfechaact = System.Convert.ToString(actyear) + "00" + System.Convert.ToString(actmonth);
}
else
{
valorfechaact = System.Convert.ToString(actyear) + "0" + System.Convert.ToString(actmonth);
}
actsecond = fecha.Second;
string label;
label = label1.Text;
string at = "@";
string filename = valorfechaact + ".csv";
string ruta3 = System.IO.Path.Combine(at, label, filename);
if (Directory.Exists(label1.Text))
{
StreamWriter wr = new StreamWriter(ruta3, true);
wr.WriteLine("1asd" + actsecond);
wr.Close();
wr.Dispose();
}
else
{
System.Console.WriteLine("no se puede escribir en el archivo");
timer1.Stop();
}
}
【问题讨论】:
-
如果文件在 Excel 中打开,您将无法覆盖该文件,因为 Excel 会锁定它。如果遇到 IO 错误,您始终可以使用唯一名称再次写入文件。
-
@AlexK。感谢您的快速回答,我该怎么做?
-
尝试/捕捉该异常?
标签: c# exception io wait ioexception