Unable to load DLL in C# - c#

how to load a dll in a c# project
error:
Unable to load DLL 'Reader.dll': The specified module could not be
found. (Exception from HRESULT: 0x8007007E)
code sample:
[DllImport("Reader.dll")]
public static extern byte OpenReader(ref IntPtr hCom, byte LinkType, string com_port);
image:

If the problem is really "cannot be found", then using ProcMon from Sysinternals will show you where the system is looking for the DLL.
However, often these sort of exceptions mean 'I found the DLL but I can't load it', and that can be because a dependency of the DLL is missing rather than the DLL itself, or because the DLL is incompatible with the app trying to load it. If your C# app is set for 'Any CPU' and you're on a 64bit machine, you'll get this sort of error loading unmanaged 32-bit DLLs.
One way to isolate the problem would be to create a simple C/C++ project which loads the DLL. (Load it dynamically with LoadLibrary if you don't have access to the import lib.) Then use Dependency Walker to profile the test harness, and it will report the names of missing DLLs.

Although the reader.dll is unable to load GPSVC.dll and IESHIMS.DLL.
i managed to make it work by running the corflags command on application.exe
the application is now marked as 32bit:
corflags application.exe /32bit+
Version : v4.0.30319
CLR Header: 2.5
PE : PE32
CorFlags : 3
ILONLY : 1
32BIT : 1
Signed : 0

I found this in another post. Maybe it will help your situation
NUnit "missing" GPSVC.DLL on Windows 7/64

If it's a simple C DLL it just needs to be in the same folder as the .exe.

For me the solution was to installing the C++ Redistrable X64 on client machine.
(Microsoft Visual C++ Redistributable for Visual Studio 2015, 2017 and 2019.)
The dll was already on the right place, in the same folder than the .exe file.
Here you found the download link:
https://support.microsoft.com/en-us/topic/the-latest-supported-visual-c-downloads-2647da03-1eea-4433-9aff-95f26a218cc0

Related

C# Dll import not working with some computers

I have a C++ dll compiled using VS2013.
I call it in my C# application like this :
[DllImport("myDLL.dll", EntryPoint = "RestartIfNecessary", CallingConvention = CallingConvention.Cdecl)]
public static extern bool RestartIfNecessary(uint uiAppId);
And it works fine.
However once the application is in prod some users have the following error :
Unable to load DLL 'myDLL.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
I can't find why this error happens on some computers. We've been able to fix the issue for some users by removing Microsoft Visual C++ 2013 Redistributable (x86) and (x64) and installing them again.
My C# application is compiled to run on x86.
I have a 64bits w10 and it works fine, so I don't know if it's related to windows.
Have you any hint to help me fixing this issue ?
EDIT: Here are the results of dependency walker :
In dependendy walker I've found 3 dll in red, I don't know if they are important:
API.dll is a third party dll (myDLL is a wrapper for this API)
The error means either myDLL.dll itself, or one of its dependent DLLs, cannot be found on the DLL search path.
Make sure myDLL.dll is placed where your app can find it. You can load myDLL.dll into Dependency Walker on the problematic computers to pinpoint any missing dependencies.

tlbimp.exe generated assembly fails to be registered using regasm.exe

I have a native COM dll that I want to build a C# interop assembly for.
I'm attempting to do this using tlbimp.exe to generate the c# assembly, and I then regasm.exe to register the assembly for transparent use via COM in another program. I'm delay signing since I'm still in a development environment and wish to do some debugging still.
The TlbImp.exe command seems to work fine, the interop file is generated.
c:\>tlbimp MyNativeComDll.dll /out:MyInteropDll.dll /publickey:myPublicKey.snk /asmversion:1.6.0.0 /delaysign
TlbImp : Type library imported to C:\MyInteropDll.dll
Microsoft .NET Framework Assembly Registration Utility version 4.6.1055.0
for Microsoft .NET Framework version 4.6.1055.0
Copyright (C) Microsoft Corporation. All rights reserved.
Unfortunately, its the regasm call that results in an error that I have no idea how to fix.
C:\>regasm C:\MyInteropDll.dll
RegAsm : error RA0000 : Could not load file or assembly 'MyInteropDll.dll, Version=1.6.0.0, Culture=neutral, PublicKeyToken=****************' or one of its dependencies. Strong name validation failed. (Exception from HRESULT: 0x8013141A)
The system I am build this all on is a x64 windows machine running Windows 7sp1.
The MyNativeComDll.dll is a x86 library.
All this is being done in a vcxproj post build command, the project being the one that builds the MyNativeComDll.dll.
I use MSBuild from the command line to build the solution.
I have both Visual Studio 2010, and Visual Studio 2015 installed, and the build fails when running the regasm command whether or not I am using VS2010's Win64 or Regular Developers command prompt. Similarly it fails in much the same fashion when using the VS2015 x64 Native Tools command prompt, or the Developer Command Prompt for VS2015.
The command I use to build the solution that contains the project causing the problem is:
C:\>msbuild MySolution.sln /p:Configuration=Release /v:n /t:Rebuild /p:Platform="Mixed Platforms"
The solution contains a number of x86 visual c++ projects and a few c# projects which are build as AnyCPU. The resultant main application is supposed to be a 32bit app. All c# projects are targeting .net 4.0.
Why would regasm report that it cannot load the file or assembly?
I've looked at the MyInteropDll.dll file in DotPeak and see absolutely no dependencies beyond mscorelib 4.0 listed. Is it a signing problem, or is it a references issue?
After looking through the post suggested by #Mangist, I recognized that the issue was a combination of registry location, and misunderstanding tlbimp.exe 's delaysign flag.
This also helped.
https://msdn.microsoft.com/en-us/library/aa302324.aspx
First, as my app is a x86 application and most of the libraries are x86, using the x64 command prompts is a bad idea, as any tool that affects the registry will write to the HKLM\Software location. Since these are x86 assemblies, any registry entries regarding them need to be written to the HKLM\Software\Wow6432Node location. This mistake was triggered by what I found regarding tlbimp.exe, as when I was using the x86 command line tools, I was still getting the regasm error, prompting me to attempt the build using the x64 command line tools, which of course also didn't work.
Tlbimp.exe indeed does have an option to delay sign an assembly, and it will do exactly that, but delay signing an assembly DOES NOT AUTOMATICALLY REGISTER THE ASSEMBLY FOR VERIFICATION SKIPPING. Registering an assembly for verification skipping requires use of the sn.exe command with the -Vr option. This adds an entry to the HKLM\Software\Wow6432Node\Microsoft\StrongName\Verification registry key when using the 32 bit sn.exe, and the HKLM\Software\Microsoft\StrongName\Verification registry key when using the 64 bit sn.exe.
It turns out that you can register a single assembly signed with a particular public key for verification skipping, or any assembly that uses a particular public key for verification skipping.
A registry entry will be created looking like
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\StrongName\Verification\*,58845dcd9090cc91]
Here * is a wildcard, and the hex number is the public key.
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\StrongName\Verification\MyInteropDll.dll,58845dcd9090cc91]
This entry is an example of allowing only the MyInteropDll.dll assembly to be skipped from signing verification.
The solution for me then is to ensure that after I make the tlbimp /delaysign call to add a command that registers the assembly for verification skipping since that's not being done automatically.
C:\>C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\sn.exe -Vr MyInteropDll.dll

Native DLL Not found

I have a program that uses Tesseract to extract text from images. I made a Native C++ DLL that is used in C# via P/Invoke. My C# application is a console x64 based and the DLL is also 64 bit.
After deploying to a Windows Server I receive an error that suggets the DLL (one I've made) does not exists. The error message is below.
System.DllNotFoundException: Unable to load DLL 'TesseractX64.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E) at Utilities.Finance.PDFParser.PDF.OCRObject.GetUTF8Text(String path, String lang, String imgPath)
I know for sure that the DLL exists in that path. The TesseractX64.DLL is placed in the same folder as the C# application so it should work without any issues.
Here is my code:
[HandleProcessCorruptedStateExceptions]
[DllImport(#"TesseractX64.dll", EntryPoint = "GetUTF8Text", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr GetUTF8Text(string path, string lang, string imgPath);
What I have tried so far:
Set the DLLImport path to a relative path for example C:\DLL\Tesseract.DLL. Still same issue.
Installed Visual C++ 2005 - 2012 both x86 and x64. Still same issue.
It works perfectly fine on my Windows 7 x64 computer that I used to develop the program.
Either:
The DLL cannot be found, or
One of the DLL's dependencies cannot be found.
Place the DLL in the same directory as the executable to ensure that it can be found.
Make sure that all the DLL's dependencies are met on each machine that needs to run your software. That will involve first working out what those dependencies are. The documentation for the DLL should tell you that information. Typically this means installing the MSVC runtime against which the DLL was linked.
You aren't allowed to redistribute the debug runtime. You'll want to make a release build of the native DLL even if the .NET code is in debug mode.

Could not load file or assembly (custom dll) - works for console but fails for web project (ASP.NET MVC 5) [duplicate]

I have this dll that I created a long time ago and use to connect to the db of a specific software that I develop for. I have had no issues for well over 4 years and countless applications with this dll.
Trying to deploy my latest creation, I get the following error:
System.IO.FileNotFoundException: Could not load file or assembly '***.dll' or one of its dependencies. The specified module could not be found.
So, for every dll I ever wrote, I always made a simple forms application to test that dll just by itself. Running that simple app yielded the same error. The dll doesn't load or use anything else than: System, System.Data, System.XML. So as far as depencies of it go, I don't see anything wrong.
By the way everything works on a dev station. The problem is limited to deployment stations. .Net and the necessary redistributables, since I do everything in C++, are deployed and working.
Running FUSLOGVW.exe showed everything as working fine.
Running depends.exe said: Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module.
I already tried rewriting the whole thing. Which yielded the same results.
Clues anyone?
EDITS
Here is the total error message:
See the end of this message for details on invoking \"
just-in-time (JIT) debugging instead of this dialog box.\"
************** Exception Text **************\"
System.IO.FileNotFoundException: Could not load file or assembly 'connectionTo.dll' or one of its dependencies. The specified module could not be found.\"
File name: 'connectionToJobboss32.dll'\"
at TESTConnection.Form1.button1_Click(Object sender, EventArgs e)\"
at System.Windows.Forms.Control.OnClick(EventArgs e)\"
at System.Windows.Forms.Button.OnClick(EventArgs e)\"
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)\"
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)\"
at System.Windows.Forms.Control.WndProc(Message& m)\"
at System.Windows.Forms.ButtonBase.WndProc(Message& m)\"
at System.Windows.Forms.Button.WndProc(Message& m)\"
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)\"
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)\"
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)\"
\"
************** Loaded Assemblies **************\"
mscorlib\"
Assembly Version: 4.0.0.0\"
Win32 Version: 4.0.30319.1 (RTMRel.030319-0100)\"
CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll\"
----------------------------------------\"
TESTConnection\"
Assembly Version: 1.0.3996.18980\"
Win32 Version: \"
CodeBase: file:///C:/Program%20Files%20(x86)/conn/TESTConnection.exe\"
----------------------------------------\"
System.Windows.Forms\"
Assembly Version: 4.0.0.0\"
Win32 Version: 4.0.30319.1 built by: RTMRel\"
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll\"
----------------------------------------\"
System.Drawing\"
Assembly Version: 4.0.0.0\"
Win32 Version: 4.0.30319.1 built by: RTMRel\"
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll\"
----------------------------------------\"
System\"
Assembly Version: 4.0.0.0\"
Win32 Version: 4.0.30319.1 built by: RTMRel\"
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll\"
----------------------------------------\"
There is no errors in the event viewer.
or one of its dependencies
That's the usual problem, you cannot see a missing unmanaged DLL with Fuslogvw.exe. Best thing to do is to run SysInternals' ProcMon utility. You'll see it searching for the DLL and not find it. Profile mode in Dependency Walker can show it too.
I had the same issue with a dll yesterday and all it referenced was System, System.Data, and System.Xml. Turns out the build configuration for the Platform type didn't line up. The dll was build for x86 and the program using it was "Any CPU" and since I am running a x64 machine, it ran the program as x64 and had issues with the x86 dll. I don't know if this is your issue or not, just thought that I would mention it as something else to check.
I recently hit this issue, the app would run fine on the developer machines and select others machines but not on recently installed machines. It turned out that the machines it did work on had the Visual C++ 11 Runtime installed while the freshly installed machines didn't. Adding the Visual C++ 11 Runtime redistributable to the app installer fixed the issue...
I had the same problem. For me, it was caused by the default settings in the local IIS server on my machine. So the easy way to fix it, was to use the built in Visual Studio development server instead :)
Newer IIS versions on x64 machines have a setting that doesn't allow 32 bit applications to run by default. To enable 32 bit applications in the local IIS, select the relevant application pool in IIS manager, click "Advanced settings", and change "Enable 32-Bit Applications" from False to True
I ran into this recently. It turned out that the old DLL was compiled with a previous version (Visual Studio 2008) and was referencing that version of the dynamic runtime libraries. I was trying to run it on a system that only had .NET 4.0 on it and I'd never installed any dynamic runtime libraries. The solution? I recompiled the DLL to link the static runtime libraries.
Check your application error log in Event Viewer (EVENTVWR.EXE). It will give you more information on the error and will probably point you at the real cause of the problem.
This answer is totally unrelated to the OP's situation, and is a very unlikely scenario for anyone else too, but just in case it may help someone ...
In my case I was getting "Could not load file or assembly 'System.Windows.Forms, Version=4.0.0.0 ..." because I had disassembled and reassembled the program using ILDAsm.exe and ILAsm.exe from .Net Framework / SDK version 2. Switching to ILDAsm.exe and ILAsm.exe from .Net Framework / SDK version 4 fixed the problem.
(Strangely, even though doing what I did may seem like an obvious error, the resulting EXE file that didn't work did indicate that it targeted .Net 4 when examined with JetBrains dotPeek.)
I had the same issue - a .dll working all the time, then my computer crashed and afterwards I had this problem of 'could not load file or assembly ....dll'
Two possible solutions: when the computer crashed there may be some inconsistent files in
C:\Users\<yourUserName>\AppData\Local\Temp\Temporary ASP.NET Files
Deleting that folder, recompiling and the error was gone.
Once I had also to delete my packages folder (I had read that somewhere else). Allow Visual Studio / nuget to install missing packages (or manually reinstall) and afterwards everything was fine again.
An easier way to determine what dependencies a native DLL has is to use Dependency Walker - http://www.dependencywalker.com/
I analysed the native DLL and discovered that it depended on MSVCR120.DLL and MSVCP120.DLL, both of which were not installed on my staging server in the System32 directory. I installed the C++ runtime on my staging server and the issue was resolved.
Had the same issue and got it resolved by making sure projects in the solution have the same configuration and platform (in my case it was Debug x64). Somehow the VIsual Studio was missing x64 for part of the projects and I edited the .sln file manually (copied the configurations and platforms from correctly built projects to the projects that were missing the settings I needed). This is what it looks like for one of the projects:
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|x64.ActiveCfg = Debug|x64
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|x64.Build.0 = Debug|x64
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|Any CPU.Build.0 = Release|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|x64.ActiveCfg = Release|x64
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|x64.Build.0 = Release|x64
But then the same error occurred for a project that had a Java file (*.jar) in the dependencies. I had to edit Environment Variables manually to create a record with this value
C:\Program Files\Java\jre1.8.0_171\bin\server
for Java's path, and put it on top of the Path items.
This fixed the issue until I updated Java on my machine. I had to edit the version number in Environment Variables to match the updated folder name.
C:\Program Files\Java\jre1.8.0_181\bin\server
1) Copy DLLs from "Externals\ffmpeg\bin" to your project's output directory (where executable stays);
2) Make sure your project is built for x86 target (runs in 32-bit mode).
Follow this thread for more

Debugging 32 bit application running in 64 bit environment

I have a 32 bit .Net 4.0 application running in a wow64 environment in a 64 bit machine.
The application encountered an error and I took a dump with 32 bit taskmanager present in C:\Windows\SysWOW64\taskmgr.exe
I am using a 32 bit Windebugger to analyze this dump. I loaded the following dlls.
1).loadby sos CLR
2).load mscordacwks ( from the client machine).
But still I am not able to use SOS commands like !clrstack,!threads etc.
I get the error:
Failed to load data access DLL, 0x80004005
What did I do wrong?
Seems that mscordacwks is not correctly loaded
One way
Try:
.cordll -u -ve -lp <absolute-path-to-directory-where-client-mscordacwks-is-placed>
The correct output should be:
CLRDLL: Loaded DLL <your-path>\mscordacwks.dll
CLR DLL status: Loaded DLL <your-path>\mscordacwks.dll
If you see:
CLR DLL status: No load attempts
rename your mscordacwks to the name suggested by .cordll:
0:000> .cordll
CLR DLL status: ERROR: Unable to load DLL mscordacwks_x86_x86_2.0.50727.3625.dll, Win32 error 0n87
and add the path where renamed mscordacwks resides to symbols:
.sympath+ <your-path>
and try your SOS command.
Other way
Get procdumpext.dll from Andrew Richard's skydrive : http://sdrv.ms/11C7S9c, load it into windbg (.load procdumpext.dll) and execute !loadsos.
Good luck! :)
I had the best results in case I didn't only get mscordacwks.dll but also sos.dll from the client machine. I even had SxS issues with those files, so getting the files from the default .NET framework directory was not helpful either. Therefore I created the mscordacwks collector which gets all possible files for you.
However, you still need to find out which version to use. You can start by looking at the .NET framework version:
lm vm clr; *** .NET CLR 4
lm vm mscorwks; *** .NET CLR 2
lm vm coreclr; *** Silverlight
(In worst case, you have two different version of .NET loaded, in which case you are out of luck).
Once you know the exact version, you can load SOS of that version by full path
.load c:\mypath\SOS_AMD64_AMD64_4.0.30319.18444.dll
Note that the collected versions of SOS.dll will also be renamed to avoid file name conflicts. For more convenience, you can create a copy and just rename it to SOS.dll.
If there are still any mscordacwks.dll issues, you can proceed as proposed by #lowleveldesign. The tool should already have renamed data access files appropriately. If you find any bug, feedback is welcome.

Categories