How do we change the assembly path in DLLImport attribute inside an if conditional statement? e.g. I want to do something like this:
string serverName = GetServerName();
if (serverName == "LIVE")
{
DLLImportString = "ABC.dll";
}
else
{
DLLImportString = "EFG.dll";
}
DllImport[DLLImportString]
You can't set attribute's value wich is calculated during runtime
You can define two methods with diff DllImports
and call them in your if statement
DllImport["ABC.dll"]
public static extern void CallABCMethod();
DllImport["EFG.dll"]
public static extern void CallEFGMethod();
string serverName = GetServerName();
if (serverName == "LIVE")
{
CallABCMethod();
}
else
{
CallEFGMethod();
}
Or you can try to Load dll dynamicaly with winapi LoadLibrary
[DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
static extern int LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);
[DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
static extern IntPtr GetProcAddress( int hModule,[MarshalAs(UnmanagedType.LPStr)] string lpProcName);
[DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]
static extern bool FreeLibrary(int hModule);
Create delegate that fits method in dll
delegate void CallMethod();
And then try to use something like that
int hModule = LoadLibrary(path_to_your_dll); // you can build it dynamically
if (hModule == 0) return;
IntPtr intPtr = GetProcAddress(hModule, method_name);
CallMethod action = (CallMethod)Marshal.GetDelegateForFunctionPointer(intPtr, typeof(CallMethod));
action.Invoke();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With