【发布时间】:2013-09-14 06:18:24
【问题描述】:
我正在尝试每 2 秒读取一次 excel 文件,该文件正在被其他 RTD 应用程序更新。
我可以通过 Oledb 连接读取此文件,但是当我尝试每 2 秒读取一次时出现问题。在 10 次尝试中,它只能读取 4-5 次,而在其他尝试中,它会抛出异常。
连接字符串
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\nids\shes.xlsm;Extended Properties="Excel 12.0 Macro;HDR=Yes;IMEX=1"
代码
//opening connection to excel file
using (OleDbConnection connection = new OleDbConnection(constr))//constr = connection string
{
try
{
connection.Open();
isconopen = true;
}
catch
{
dispatcherTimer2.Start();
connection.Close();
isconopen = false;
}
// If connection is ok , then query sheet
if (isconopen == true)
{
strcon = "SELECT * FROM [" + dsheet + "]";
using (OleDbDataAdapter adapter = new OleDbDataAdapter(strcon, connection))
{
try
{
adapter.Fill(result);
isread = true;
adapter.Dispose();
connection.Close();
}
catch
{
isread = false;
dispatcherTimer2.Start();
adapter.Dispose();
connection.Close();
}
}
}
//if able to retrieve data then call some other function
if (isread == true)
{
converToCSV(0);// for further processing
}
请帮助我,我从过去 1 个月开始尝试这个。请帮帮我吧
【问题讨论】:
-
嗯,你需要得到什么?您不能简单地捕获异常并在(比方说)500 毫秒后重试吗?如果这不可行,您可以简单地使用 File.Copy 制作副本,然后打开副本。遗憾的是,您不能要求 OleDB 驱动程序在实例之间共享文件。
-
@Adriano,首先感谢您给我们时间,我正在做同样的重试,但正在寻找更好的方法,复制文件的问题是文件数据没有保存在硬盘上。这个excel文件是在电脑上打开的。您能否分享一下代码/方式,我可以每 2 秒保存/复制该文件,然后读取该文件
-
我肯定会按照@Adriano 在他的回复中的建议使用 FileSystemWatcher