我正在尝试在运行时动态加载适用于Devart.SQLite.DLL的x86 / x64版本的SQLite3.DLL。我无法控制预先将适当版本的DLL安装到应用程序根目录,因此必须从应用程序根目录中的/x86或/x64子目录中获取正确版本。
有没有想法如何实现这一点?坦白地说,我完全迷失了方向。到目前为止,我的代码是:
有没有想法如何实现这一点?坦白地说,我完全迷失了方向。到目前为止,我的代码是:
Public Sub New()
LoadAssembly("sqlite3.dll", True)
End Sub
Private Function GetAssemblyPath(ByVal assembly As String, ByVal version As String) As String
Return Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().Location) & "\" & version & "\" & assembly
End Function ' GetAssemblyName
<Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint:="LoadLibraryW")> _
Public Shared Function LoadLibraryW(<Runtime.InteropServices.InAttribute()> <Runtime.InteropServices.MarshalAsAttribute(Runtime.InteropServices.UnmanagedType.LPWStr)> lpLibFileName As String) As IntPtr
End Function
Private Sub LoadAssembly(ByVal myAssembly As String, Optional ByVal doLoadLibrary As Boolean = False)
Dim an As AssemblyName
Dim filename As String
Dim version As String
If UIntPtr.Size = 8 Then version = "x64" Else version = "x86"
filename = GetAssemblyPath(myAssembly, version)
Try
If doLoadLibrary Then
HostLog.WriteEntry(filename, EventLogEntryType.Information)
Dim ptr As IntPtr = LoadLibraryW(filename)
HostLog.WriteEntry(ptr.ToString(), EventLogEntryType.Information)
Else
an = AssemblyName.GetAssemblyName(filename)
AppDomain.CurrentDomain.Load(an)
End If
Catch ex As Exception
HostLog.WriteEntry(ex.Message, EventLogEntryType.Error)
End Try
End Sub ' LoadAssembly
编辑 如评论中提到的,我未能指明在尝试加载sqlite3.dll时实际收到的错误。结果是,我的App.Config中缺少以下内容:
<system.data>
<DbProviderFactories>
<remove invariant="Devart.Data.SQLite" />
<add name="dotConnect for SQLite"
invariant="Devart.Data.SQLite"
description="Devart dotConnect for SQLite"
type="Devart.Data.SQLite.SQLiteProviderFactory, Devart.Data.SQLite, Version=4.2.122.0, Culture=neutral, PublicKeyToken=09af7300eec23701" />
</DbProviderFactories>
</system.data>
一旦我将这个代码添加到App.Config中,我的之前的代码示例按预期工作。感谢所有人的帮助。