我试图每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"
Run Code Online (Sandbox Code Playgroud)
码
//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
}
Run Code Online (Sandbox Code Playgroud)
请帮助我,我从最近1个月开始尝试这个.请帮助请帮帮我
遗憾的是OleDB驱动程序默认情况下会打开文件,然后当别人使用它时你就无法打开它,即使只是为了阅读.
两个考虑:
这就是说我建议你应该在短暂的停顿后首先尝试打开它,如果它仍然在使用(你不能等待更多),那么你可以复制并打开它.
我假设你在HandlExcelFile()
函数中有你的代码:
void HandleExcelFile(string path)
{
try
{
// Function will perform actual work
HandleExcelFileCore(path);
}
catch (Exception) // Be more specific
{
Thread.Sleep(100); // Arbitrary
try
{
HandleExcelFileCore(path);
}
catch (Exception)
{
string tempPath = Path.GetTempFileName();
File.Copy(path, tempPath);
try
{
HandleExcelFileCore(tempPath);
}
finally
{
File.Delete(tempPath);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
代码有点难看,所以只考虑它是编写自己的函数的起点.
注意事项:
未经测试的解决方案:
我没有尝试这个,所以你必须自己做.实际上(我最初错了)你可以打开一个只读连接(通过扩展属性).如果这仅适用于连接或文件句柄和连接,则不会记录.无论如何,让我们尝试将您的连接字符串更改为:
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\nids\shes.xlsm;Extended Properties="Excel 12.0 Macro;HDR=Yes;IMEX=1;ReadOnly=true"
Run Code Online (Sandbox Code Playgroud)
只是增加了一个ReadOnly=true
在年底Extended Properties
.
其他方案:
FileSystemWatcher
,只有在通知它已被更改时才会读取该文件. 归档时间: |
|
查看次数: |
10154 次 |
最近记录: |