2011-06-23 21 views
0

次のコードは、ファイルに初めてアクセスして行数をカウントするときに正しく機能します。しかし、同じファイルを開いてデータを読み込もうとすると、ExcelConnection.Open()にスローされ、そのファイルにアクセスする権限がないか、既に使用されているというエラーが表示されます。ファイルが最初に接続された後にファイルが解放されていない理由は何ですか?OLDB経由でExcelに接続するときのファイルのアクセス許可エラー

public static DataSet GetExcelWorkSheet(string pathName, string fileName) 
     { 
      string fileExtention = System.IO.Path.GetExtension(fileName).ToLower(); 

      OleDbConnection ExcelConnection = new OleDbConnection(fileExtention == ".xls" ? 
       @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + @"\" + fileName + ";Extended Properties=\"Excel 8.0;HDR=No;IMEX=1;ReadOnly=true;\"" : 
       @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + @"\" + fileName + ";Extended Properties=\"Excel 12.0;HDR=No;IMEX=1;ReadOnly=true;\""); 
      OleDbCommand ExcelCommand = new OleDbCommand(); 
      ExcelCommand.Connection = ExcelConnection; 
      OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand); 
      ExcelConnection.Open(); 

      // DataTable ExcelSheets = ExcelConnection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); 
      DataTable ExcelSheets = ExcelConnection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null); 

      string CheckSheetName = ExcelSheets.Rows[0]["TABLE_NAME"].ToString(); 
      string SpreadSheetName; 
      int useMe = -1; 

      if (CheckSheetName.ToUpper() != "SHEET1$")     // Ok, they have renamed things 
      { 
       if (CheckSheetName.Substring(0, 5).ToUpper() == "SHEET") 
       // if it does START with sheet then look for anything that 
       // DOES NOT start with sheet 
       { 
        for (int x = 0; x < ExcelSheets.Rows.Count; x++) 
        { 
         if (ExcelSheets.Rows[x]["TABLE_NAME"].ToString().Substring(0, 5).ToUpper() != "SHEET") // If is does not equal sheet then use it 
         { 
          useMe = x; 
         } 
        } 
       } 
      } 

      SpreadSheetName = string.Format("[{0}]", useMe == -1 ? CheckSheetName : ExcelSheets.Rows[useMe]["TABLE_NAME"].ToString()); 

      try 
      { 
       DataSet ExcelDataSet = new DataSet(); 
       ExcelCommand.CommandText = @"SELECT * FROM " + SpreadSheetName; 
       ExcelAdapter.Fill(ExcelDataSet); 
       return ExcelDataSet; 
      } 
      catch (Exception) 
      { 
       ExcelConnection.Close(); 
       return new DataSet(); 
      } 
      finally 
      { 
       // Clean up. 
       if (ExcelConnection != null) 
       { 
        ExcelConnection.Close(); 
        ExcelConnection.Dispose(); 
       } 
       if (ExcelSheets != null) 
       { 
        ExcelSheets.Dispose(); 
       } 
      } 
     } 
    } 

答えて

0

ファイルが読み込まれたか、あなたが持っている操作がodneが完了した後、あなたはconnetionを閉じる必要があります....

ExcelConnection.Close();

+0

私はfinallyブロックでこれを行っています。最初のプロセスをステップ実行すると、最終的には最終的に正しく実行され、接続もデータオブジェクトも閉じられます。 – Seth

関連する問題