如果Excel xls文件已损坏,OleDbConnection会锁定该文件



我有一个遗留代码,它将Excel(*.xls)导入数据库,然后在处理后将文件移动到特定目录。

该代码运行良好,除非在一种情况下,文件已损坏(即使是MS Excel也无法打开它)!在这种情况下,在打开连接时抛出了System.AccessViolationException

以下是代码的样子:

        string connectionString = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1""", filePath);
        OleDbConnection connection = new OleDbConnection(connectionString);
        try
        {
            connection.ConnectionString = connectionString;
            connection.Open(); //<<<--- exception throws here
            //file processing
        }
        catch (Exception e)
        {
            //exception handling
        }
        finally
        {
            connection.Close();
            connection.Dispose();
            connection = null;
            GC.Collect();
        }

以下是异常详细信息。。。

System.AccessViolationException was caught
  Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
  Source=System.Data
  StackTrace:
       at System.Data.Common.UnsafeNativeMethods.IDBInitializeInitialize.Invoke(IntPtr pThis)
       at System.Data.OleDb.DataSourceWrapper.InitializeAndCreateSession(OleDbConnectionString constr, SessionWrapper& sessionWrapper)
       at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection)
       at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject)
       at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)
       at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
       at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
       at System.Data.OleDb.OleDbConnection.Open()

正如你所看到的,我正在捕捉并处理这个异常,然后当代码试图将文件移动到另一个目录时,我得到了以下异常:

System.IO.IOException occurred
  Message=The process cannot access the file because it is being used by another process.
  Source=mscorlib
  StackTrace:
       at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
       at System.IO.__Error.WinIOError()
       at System.IO.File.Move(String sourceFileName, String destFileName)

我试着使用另一个库,比如LinqToExcel,但发现它内部使用了与我相同的实现,那么它也有同样的问题!

我还尝试在连接关闭后运行垃圾收集器(如您在上面的代码中看到的),但遇到了同样的问题!

有什么想法吗?

我试图绕过这个问题的主要解决方案,但没有结果:(

我甚至检查了.NET Framework代码,可以在代码中的某个位置看到文件句柄,但不幸的是,未能调试代码:(

我试图反编译.NET Framework代码,但也失败了:(

最后。最后,我应该使用另一个解决方案,因为根据生产机器中是否存在MSOffice是不可选择的,所以我选择了ExcelDataReader,这是一个开源库,可以将*.xls文件作为二进制流读取,下面是最终代码的样子:

using (FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
    using (IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream, true))
    {
        excelReader.IsFirstRowAsColumnNames = true;
        var excelFileDataSet = excelReader.AsDataSet();
        var sheetDataTable = excelFileDataSet.Tables["sheetName"];
        //other file processing code...
    }
}    

这个解决方案对我有效!

我现在也有同样的问题,我唯一的解决方案是使用Microsoft.Office.Interop.excel读取excel文件,并设置MsoFileValidationMode=msoFileValidationSkip;

Excel.ApplicationxlApp=新建Excel.Application();Excel.Workbook xlWorkbook;

        System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
        System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
        **xlApp.FileValidation = MsoFileValidationMode.msoFileValidationSkip;** 
        xlWorkbook = xlApp.Workbooks.Open(@"C:my file.xls");
        Excel.Sheets xlWorksheet = xlWorkbook.Worksheets;
        Excel.Worksheet worksheet = (Excel.Worksheet)xlWorksheet.get_Item(3);
        for (int i = 1; i <= 10; i++)
        {
            Excel.Range range = worksheet.get_Range("A" + i.ToString(), "B" + i.ToString()); ; //UsedRange;
            System.Array myvalues = (System.Array)range.Cells.Value2;

            string[] strArray = ConvertToStringArray(myvalues);
            foreach (string item in strArray)
            {   
                MessageBox.Show(item);
            }
        }

运行良好

相关内容

  • 没有找到相关文章

最新更新