Programming

BadImageFormatException 문제 해결

procodes 2020. 8. 24. 21:38
반응형

BadImageFormatException 문제 해결


Visual Studio 2010을 사용하고 전체 .NET Framework 4를 대상으로하는 C #으로 작성된 Windows 서비스가 있습니다. 디버그 빌드에서 실행하면 서비스가 예상대로 실행됩니다. 그러나 릴리스 빌드에서 실행하면 System.BadImageFormatException이 발생합니다 (아래 세부 정보). 나는 인터넷에서 해결책을 찾고 있었지만 지금까지 내가 찾은 모든 것이 해결책을 찾는 데 도움이되지 않았습니다.

이 문제는 Windows 7 64 비트 (dev) 및 Windows XP SP3 32 비트 (대상) 시스템 모두에 존재합니다.

지금까지 시도한 내용은 다음과 같습니다.

  • Platform Target과 같은 확인 된 빌드 설정은 모두 동일합니다 (x86).
  • 어셈블리 바이너리가 유효한지 확인하기 위해 / verbose 옵션과 함께 peverify를 사용했습니다.
  • fuslogvw를 사용하여로드 문제를 찾습니다.
  • CheckAsm을 사용하여 누락 된 파일 또는 어셈블리를 찾았습니다.

이 모든 수표는 아무것도 변경하지 않았습니다. 회사 마스터의 비밀을 보호하기 위해 일부 이름이 변경된 다음 예외 정보의 전체 텍스트를 포함했습니다.

System.BadImageFormatException이 처리되지 않았습니다.
  메시지 = 파일 또는 어셈블리 'XxxDevices, 버전 = 1.0.0.0, Culture = neutral, PublicKeyToken = null'또는 해당 종속성 중 하나를로드 할 수 없습니다. 잘못된 형식으로 프로그램을로드하려고했습니다.
  소스 = XxxDevicesService
  FileName = XxxDevices, 버전 = 1.0.0.0, Culture = neutral, PublicKeyToken = null
  FusionLog = 어셈블리 관리자로드 : C : \ Windows \ Microsoft.NET \ Framework64 \ v4.0.30319 \ clr.dll
실행 파일 c : \ Dev \ TeamE \ bin \ Release \ XxxDevicesService.vshost.exe에서 실행
--- 자세한 오류 로그는 다음과 같습니다. 

=== 사전 바인딩 상태 정보 ===
로그 : 사용자 = XXX
로그 : DisplayName = XxxDevices, 버전 = 1.0.0.0, Culture = neutral, PublicKeyToken = null
 (완전히 지정됨)
로그 : Appbase = file : /// c : / Dev / TeamE / bin / Release /
로그 : 초기 PrivatePath = NULL
어셈블리 호출 : XxxDevicesService, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null.
===
LOG :이 바인딩은 기본로드 컨텍스트에서 시작됩니다.
로그 : 응용 프로그램 구성 파일 사용 : c : \ TeamE \ bin \ Release \ XxxDevicesService.vshost.exe.Config
로그 : 호스트 구성 파일 사용 : 
로그 : C : \ Windows \ Microsoft.NET \ Framework64 \ v4.0.30319 \ config \ machine.config에서 컴퓨터 구성 파일 사용.
LOG : 현재 참조에 정책이 적용되지 않습니다 (개인, 사용자 지정, 부분 또는 위치 기반 어셈블리 바인딩).
LOG : 새 URL 파일 다운로드 시도 : ///c:/TeamE/bin/Release/XxxDevices.DLL.
오류 : 어셈블리 설정을 완료하지 못했습니다 (hr = 0x8007000b). 조사가 종료되었습니다.

  StackTrace :
       XxxDevicesService.Program.Main (String [] args)에서
       System.AppDomain._nExecuteAssembly (RuntimeAssembly 어셈블리, String [] args)에서
       Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly ()에서
       System.Threading.ExecutionContext.Run (ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)에서
       System.Threading.ExecutionContext.Run (ExecutionContext executionContext, ContextCallback callback, Object state)에서
       System.Threading.ThreadHelper.ThreadStart ()에서
  InnerException : 

Platform Target과 같은 확인 된 빌드 설정은 모두 동일합니다 (x86).

그것은 충돌 로그가 말하는 것이 아닙니다.

어셈블리 관리자 : C : \ Windows \ Microsoft.NET \ Framework64

64 비트 버전의 프레임 워크가있는 이름 64참고하십시오 . 클래스 라이브러리 프로젝트가 아닌 EXE 프로젝트 에서 대상 플랫폼 설정을 설정하십시오 . XxxDevicesService EXE 프로젝트는 프로세스의 비트를 결정합니다.


일주일 내내이 문제를 해결하기 위해 책상에 머리를 두드리는 것을 멈춘 후, 나는 나를 위해 일한 것을 공유하고 있습니다. Win7 64 비트, 32 비트 Oracle 클라이언트가 있고 Oracle 비트로 인해 x86 플랫폼에서 실행되도록 MVC 5 프로젝트를 설정했습니다. 같은 오류가 계속 발생했습니다.

파일 또는 어셈블리 'Oracle.DataAccess'또는 해당 종속성 중 하나를로드 할 수 없습니다. 잘못된 형식으로 프로그램을로드하려고했습니다.

NuGet 패키지를 다시로드하고, 다른 앱에서 다른 앱에서 작동했던 DLL의 복사본을 사용하고, 종속 어셈블리의 코드베이스를 내 프로젝트의 bin 폴더를 가리 키도록 설정하고, CopyLocal을 true 또는 false로 시도하고 모든 것을 시도했습니다 . 마지막으로 코드를 확인하고 싶었고 새로운 계약자로서 Subversion을 설정하지 않았습니다. VS에 연결하는 방법을 찾는 동안 나는 대답을 넘어 섰습니다. 내가 찾은 것은 Tools => Options 메뉴의 Projects and Solutions => Web Projects 섹션에서 "Use the 64 bit version of IIS Express for Web Sites and Projects"옵션의 선택을 취소하는 것입니다.


What I found worked was checking the "Use the 64 bit version of IIS Express for Web Sites and Projects" option under the Projects and Solutions => Web Projects section under the Tools=>Options menu.


It can typically occur when you changed the target framework of .csproj and reverted it back to what you started with.

Make sure 1 if supportedRuntime version="a different runtime from cs project target" under startup tag in app.config.

Make sure 2 That also means checking other autogenerated or other files in may be properties folder to see if there is no more runtime mismatch between these files and one that is defined in .csproj file.

These might just save you lot of time before you start trying different things with project properties to overcome the error.


I had the same problem even though I have 64-bit Windows 7 and i was loading a 64bit DLL b/c in Project properties | Build I had "Prefer 32-bit" checked. (Don't know why that's set by default). Once I unchecked that, everything ran fine


You can also get this exception when your application target .NET Framework 4.5 (for example) and you have the following app.config :

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v2.0.50727" />
    <supportedRuntime version="v4.0" />
  </startup>
</configuration>

When trying to launch the debug of the application you will get the BadImageFormatException.

Removing the line declaring the v2.0 version will clear the error.

I had this issue recently when I tried to change the target platform from an old .NET 2.0 project to .NET 4.5.


Background

We started getting this today when we switched our WCF service from AnyCPU to x64 on a Windows 2012 R2 server running IIS 6.2.

First we checked the only referenced assembly 10 times, to ensure it was not actually an x86 dll. Next we checked the application pool many times to ensure it was not enabling 32 bit applications.

On a whim I tried toggling the setting. It turns out the application pools in IIS were defaulting to an Enable 32-Bit Applications value of False, but IIS was ignoring it on our server for some reason and always ran our service in x86 mode.

Solution

  • Select the app pool.
  • Choose Set Application Pool Defaults... or Advanced Settings....
  • Change Enable 32-Bit Applications to True.
  • Click OK.
  • Choose Set Application Pool Defaults... or Advanced Settings... again.
  • Change Enable 32-Bit Applications back to False.
  • Click OK.

I fixed this issue by changing the web app to use a different "Application Pool".


For anyone who may arrive here at a later time....Nothing worked for me. All my assemblies were fine. I had an app config in one of my Visual Studio Projects that shouldn't have been there. So make sure your app config file is needed.

I deleted the extra app config and it worked.


Determine the application pool used by the application and set the property of by setting Enable 32 bit applications to True. This can be done through advance settings of the application pool.


When building apps for 32-bit or 64-bit platform (My experience is with Visual Studio 2010), don't rely on the Configuration Manager to set the correct platform for the executable. Even if the CM has x86 selected for the application, check the project properties (Build tab): it might still say "Any CPU" there. And if you run an "Any CPU" executable on a 64-bit platform, it will run in 64-bit mode and refuse to load your accompanying DLLs that were built for the x86 platform.


Remove your dependency on System.Runtime in your Web.Config, it worked for me:

<dependentAssembly>
        <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.10.0" newVersion="4.0.10.0" />
</dependentAssembly>

For .NET Core, there is a Visual Studio 2017 bug that can cause the project properties Build page to show the incorrect platform target. Once you discover that the problem is, the workarounds are pretty easy. You can change the target to some other value and then change it back.

Alternatively, you can add a runtime identifier to the .csproj. If you need your .exe to run as x86 so that it can load a x86 native DLL, add this element within a PropertyGroup:

<RuntimeIdentifier>win-x86</RuntimeIdentifier>

A good place to put this is right after the TargetFramework or TargetFrameworks element.


I am surprised that no-one else has mentioned this so I am sharing in case none of the above help (my case).

What was happening was that an VBCSCompiler.exe instance was somehow stuck and was in fact not releasing the file handles to allow new instances to correctly write the new files and was causing the issue. This became apparent when I tried to delete the "bin" folder and it was complaining that another process was using files in there.

Closed VS, opened task manager, looked and terminated all VBCSCompiler instances and deleted the "bin" folder to get back to where I was.

Reference: https://developercommunity.visualstudio.com/content/problem/117596/vbcscompilerexe-process-stays-runing-after-exiting.html


Target build x64 Target Server Hosting IIS 64 Bit

If the application build is targeting 64-Bit OS then on the 64-Bit server hosting the IIS,Set the enable 32 bit application on the app pool running the website/web application to false.

enter image description here


For anyone who may arrive here at a later time...
For Desktop solution I got BadImageFormatException exception.
All project's build options was fine (all x86). But StartUp project of solution was changed to some other project(class library project).

Changing StartUp project to the original(.exe application project) was a solution in my case


When I faced this issue the following solved it for me:

I was calling a OpenCV dll from inside another exe, my dll did not contained the already needed opencv dlls like highgui, features2d, and etc available in the folder of my exe file. I copied all these to the directory of my exe project and it suddenly worked.


This error "Could not load file or assembly 'example' or one of its dependencies. An attempt was made to load a program with an incorrect format" is typically caused by an incorrect application pool configuration.

  1. Ensure that the AppPool your site is currently running on has "Enable 32-Bit Applications" set to False.
  2. Ensure you are using the correct version for your platform.
  3. If you are getting this error on a web site, ensure that your application pool is set to run in the correct mode (3.0 sites should run in 64 bit mode)
  4. You should also make sure that the reference to that assembly in visual studio is pointing at the correct file in the packages folder.
  5. Ensure you have the correct version of the dll installed in the GAC for 2.0 sites.
  6. This can also be caused by WSODLibs being promoted with the web project.

참고URL : https://stackoverflow.com/questions/8996653/troubleshooting-badimageformatexception

반응형