0

我们正在阅读 xls 文件,该文件会定期从外部链接更新。我们有一个循环,它在 200 毫秒的间隔后读取相同的文件。读取文件 1000 多次后,我们收到错误

“Microsoft Jet 数据库引擎无法打开文件 ''。它已被其他用户以独占方式打开,或者您需要权限才能查看其数据。”

连接字符串如下:

Provider=Microsoft.Jet.OLEDB.4.0;数据源=D:\FeedFiles\TESTING1.xls;Extended Properties="Excel 8.0;HDR=YES;IMEX=1;Importmixedtypes=text;typeguessrows=0;"

一段时间后,它开始给出“找不到可安装的 ISAM”。

代码如下:

String xlsConnString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;Importmixedtypes=text;typeguessrows=0;""", feedFiles.FullName);

OleDbDataAdapter dataAdapter = new OleDbDataAdapter(xlsQuery, xlsConnString);
while (true)
{
    try
    {
        //Exception handling if not able to read xls file.
        DataSet dataSet = new DataSet();
        dataAdapter.Fill(dataSet);
        String fileName = dirstr + "Temp-";
        System.IO.StreamWriter file = new System.IO.StreamWriter(fileName + ".tmp");

        file.WriteLine(dataSet.GetXml());
        file.Close();

        try
        {
            File.Replace(fileName + ".tmp", dirstr + "Temp-" + filecount.ToString() + ".xml", null);
        }
        catch (Exception ex)
        {
            try
            {
                File.Move(fileName + ".tmp", dirstr + "Temp-" + filecount.ToString() + ".xml");
            }
            catch
            {
                Thread.Sleep(xlsThreadSleep);
            }
        }

        filecount++;
        if (filecount > maxFileCnt)
        {
            filecount = 0;
        }
        dataSet.Clear();
        dataSet = null;

        Thread.Sleep(xlsThreadSleep);
    }
    catch (Exception ex)
    {
        txtlog.BeginInvoke(new DelegateForTxtLog(functionFortxtLog), "Exception occured > " + ex.Message);
        feedFileIndex++;

        if (feedFileIndex == feedFiles.Length)
        {
            feedFileIndex = 0;
        }
        dataAdapter.Dispose();
        dataAdapter = null;

        Thread.Sleep(xlsThreadSleep * 20);

        xlsConnString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;Importmixedtypes=text;typeguessrows=0;""", feedFiles[feedFileIndex].FullName);
        txtlog.BeginInvoke(new DelegateForTxtLog(functionFortxtLog), "Trying connecting with connection string > " + xlsConnString);

        dataAdapter = new OleDbDataAdapter(xlsQuery, xlsConnString);
        txtlog.BeginInvoke(new DelegateForTxtLog(functionFortxtLog), "Now reading file > " + feedFiles[feedFileIndex].FullName);
    }
}
4

1 回答 1

1

连接字符串的格式不正确。尝试这个:

String xlsConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=
             {0};Extended Properties=\"Excel 8.0;HDR=YES;
             IMEX=1;Importmixedtypes=text;typeguessrows=0;\"", feedFiles.FullName);
于 2012-06-11T05:00:26.977 回答