读取xls文件后“无法找到可安装的ISAM”C#异常

时间:2012-06-11 04:54:58

标签: c# .net excel isam

我们正在阅读xls文件,该文件定期从外部链接更新。我们有循环,在200ms的间隔后读取相同的文件。读取文件超过1000次后,我们收到错误

  

“Microsoft Jet数据库引擎无法打开文件”。它已由其他用户独占打开,或者您需要获得查看其数据的权限。“

连接字符串如下:

  

Provider = Microsoft.Jet.OLEDB.4.0; Data Source = D:\ FeedFiles \ TESTING1.xls; Extended Properties =“Excel 8.0; HDR = YES; IMEX = 1; Importmixedtypes = text; typeguessrows = 0;”< / p>

过了一段时间,它开始提供“无法找到可安装的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);
    }
}

1 个答案:

答案 0 :(得分: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);