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

时间:2015-03-26 17:39:26

标签: c# .net excel oledbconnection filehandle

我有遗留代码将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,但发现它在内部使用与我相同的实现,那么它也有同样的问题!

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

任何想法?

2 个答案:

答案 0 :(得分:0)

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

Excel.Application xlApp = new 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);
            }

        }

......运作良好

答案 1 :(得分:0)

我尝试在问题中找到主要解决方案但没有结果:(

我甚至检查了.NET Framework代码并且可以在代码中的某处看到文件句柄,但遗憾的是无法调试代码:(

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

最后。它结束了我应该使用另一种解决方案,因为根据生产机器中MS Office的存在不是一种选择,我去了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...
    }
}    

这个解决方案适合我!