日期:2014-05-18  浏览次数:21105 次

C# 操作.mdb文件出现.ldb锁死文件 无法删除.mdb文件
有个问题困扰我很长时间了 access数据库操作 当访问.mdb文件会出现一个.ldb锁死文件 我想用代码删除.mdb文件 可是操作不了 提示被另一个程序调用

------解决方案--------------------
请参考我的代码
c#做法类似

Dim SaveFile As String = "F:test.mdb"
Dim SaveFileName As String = SaveFile
Dim Cat As New ADOX.Catalog

Cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + SaveFile + ";")
Dim tbl As New ADOX.Table()
tbl.ParentCatalog = Cat
tbl.Name = "Table1"

'增加字段
tbl.Columns.Append("id", ADOX.DataTypeEnum.adInteger)
tbl.Columns.Append("工况", ADOX.DataTypeEnum.adVarWChar, 255)
tbl.Columns.Append("船舶运动", ADOX.DataTypeEnum.adVarWChar, 255)
tbl.Columns.Append("纵荡加速度", ADOX.DataTypeEnum.adVarWChar, 255)
tbl.Columns.Append("横荡加速度", ADOX.DataTypeEnum.adVarWChar, 255)
tbl.Columns.Append("垂荡加速度", ADOX.DataTypeEnum.adVarWChar, 255)
tbl.Columns.Append("测试", ADOX.DataTypeEnum.adVarWChar, 255)
tbl.Columns.Append("测试2", ADOX.DataTypeEnum.adVarBinary)

'主键
tbl.Columns("id").Properties("autoincrement").Value = True
tbl.Keys.Append("PrimaryKey", ADOX.KeyTypeEnum.adKeyPrimary, "id")
Cat.Tables.Append(tbl)



'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''''''''''写入ACCESS数据库
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim ConnectionStr As String = "Provider=Microsoft.jet.OLEDB.4.0;Data Source=" & SaveFile
Dim myConn As New OleDbConnection
myConn.ConnectionString = ConnectionStr
Dim sqlString As String
Dim myCmd As OleDb.OleDbCommand = Nothing
myConn.Open()
sqlString = "INSERT INTO Table1 (工况,船舶运动,纵荡加速度,横荡加速度,垂荡加速度,测试,测试2) "
sqlString = sqlString + vbCrLf + "VALUES(@工况,@船舶运动,@纵荡加速度,@横荡加速度,@垂荡加速度,@测试,@测试2)"
For i As Integer = 1 To 200
myCmd = New OleDbCommand(sqlString, myConn)
myCmd.Parameters.AddWithValue("@工况", "满载")
myCmd.Parameters.AddWithValue("@船舶运动", "纵摇")
myCmd.Parameters.AddWithValue("@纵荡加速度", i)
myCmd.Parameters.AddWithValue("@横荡加速度", i)
myCmd.Parameters.AddWithValue("@垂荡加速度", i)
myCmd.Parameters.AddWithValue("@测试", i)
myCmd.Parameters.AddWithValue("@测试2", i * i)
myCmd.ExecuteNonQuery()
Next
myCmd.Dispose()
myCmd = Nothing
myConn.Close()
myConn.Dispose()
myConn = Nothing

'释放ldb文件的关键
Cat.ActiveConnection.Close()

System.Runtime.InteropServices.Marshal.ReleaseComObject(tbl)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(tbl)

System.Runtime.InteropServices.Marshal.ReleaseComObject(Cat)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Cat)
Cat = Nothing
GC.WaitForPendingFinalizers()
GC.Collect()

GC.WaitForPendingFinalizers()
GC.Collect()

If My.Computer.FileSystem.FileExists(SaveFile) = True Then
My.Computer.FileSystem.DeleteFile(SaveFile)
End If