Home » .Net Framework

System.BadImageFormatException - can't solve it


I'm using Visual Studio 2010, running in Windows 7 X64
I was trying to create a simple WCF implementation of duplex communication.
Sadly enough I got stuck very quickly.

I have 3 projects:
- Service library with simple service contract and the implementation
- ServiceHost: Hosting the service library via SelfHosting
- Client: Consuming a method from the WCF service

Something I immediately noticed that the Service library had Any CPU as platform . The other two had x86 as platform .
At this point I had no idea I would get this error, so this didn't really bother me.

Then I started the service library using the built in wcfsvchost.exe. Service was hosted without a problem.
Then I wanted to host my service via my own host. Here I got my first experience with System.BadImageFormatException. I had no idea what it was at that point.
So I was stuck and did some googling. If I understand correctly the platform of all the dlls etc. need to be the same.  if someone can explain me a little better. Please do.

Anyway so I though I would change the platform of the service library because this had Any CPU instead of x86. So I tried to do it via the Project settings and the configuration manager. But the problem is I had not the option to change it. Then I unloaded the project, looked what the other .csproj looked like it and changed the values there. Reloaded it and everything was fine. Now it had the correct platform, x86 . Ok so let's test run the service library..BOOM System.BadImageFormatException

System.BadImageFormatException: Could not load file or assembly 'file:///C:\Users\Sven\documents\visual studio 2010\Projects\DuplexDemo\CustomerService2\bin\Debug\CustomerService2.dll' or one of its dependencies. An attempt was made to load a program with an incorrect format.
File name: 'file:///C:\Users\Sven\documents\visual studio 2010\Projects\DuplexDemo\CustomerService2\bin\Debug\CustomerService2.dll'
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
   at Microsoft.Tools.SvcHost.ServiceHostHelper.LoadServiceAssembly(String svcAssemblyPath)

=== Pre-bind state information ===
LOG: User = Sven-PC\Sven
LOG: Where-ref bind. Location = C:\Users\Sven\documents\visual studio 2010\Projects\DuplexDemo\CustomerService2\bin\Debug\CustomerService2.dll
LOG: Appbase = file:///C:/Users/Sven/documents/visual studio 2010/Projects/DuplexDemo/CustomerService2/bin/Debug
LOG: Initial PrivatePath = NULL
Calling assembly : (Unknown).
LOG: This bind starts in LoadFrom load context.
WRN: Native image will not be probed in LoadFrom context. Native image will only be probed in default load context, like with Assembly.Load().
LOG: Using application configuration file: C:\Users\Sven\documents\visual studio 2010\Projects\DuplexDemo\CustomerService2\bin\Debug\CustomerService2.dll.config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.21006\config\machine.config.
LOG: Attempting download of new URL file:///C:/Users/Sven/documents/visual studio 2010/Projects/DuplexDemo/CustomerService2/bin/Debug/CustomerService2.dll.
ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated.

So now that I had changed the platform the service library wouldn't run anymore. So now I'm stuck and I seek some solutions.

Can anyone tell me what's going on?
Don't think the code is having errors because it's all plain vanilla WCF and before it was working.

Please help me out

2 Answers Found


Answer 1

I under stand what you mean. But I also don't know how to solve  it. Wish someone know. I am sorry.
Antivirus System Pro Removal - How to Get Rid of Antivirus system  Pro

Answer 2



Your service host is using the 64bit framework.  x86 won't run in it.



Im trying o build my WCF project and im developing on Visual Studio with x64


Ive trid every configuration and when i use the x64 dll's I get the following error:

System.IO.FileLoadException: Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.


When i use the x86 dll's I get the following error:

System.BadImageFormatException: Could not load file or assembly 'StreamTools.NET, Version=, Culture=neutral, PublicKeyToken=d264bf7150202654' or one of its dependencies. An attempt was made to load a program with an incorrect format.


Anyone know how to fix this?


This happens when I use the following

      <TestContainer Include="$(SolutionRoot)\CRCTest\TestAll.orderedtest" />

From previous posts it looks like webtest and loadtest are supported in SP1. But I have Sp1 and Team System development system installed and I get

TeamFoundation.Build.targets : warning MSB4018: System.BadImageFormatException: Could not load file or assembly

I am not sure why this would not work and that it would work directly with MSTest.


I'm trying to make a simple web user control but when I add a SharePoint component such as Microsoft.Office.Server I get this error when I debug/release it:

Exception Details: System.BadImageFormatException: Could not load file or assembly 'Microsoft.Office.Server.Search, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c' or one of its dependencies. An attempt was made to load a program with an incorrect format.

When I add Microsoft.SharePoint (Windows SharePoint Services) to my references I get almost the same error : Could not load file or assembly 'Microsoft.SharePoint.Search......
The webpart with the web user control doesn't work either in a SharePoint site.
I've googled alot on this problem which clearly has to do with the 64 bit environment. I tried alot too but no luck.
What shall I try next?

Hi guys,

I develop app (.Net 2.0) that can be launched locally and from IE (through IEExec.exe). On 32 bit OS it works fine but there is problem with 64 bit OS. When I start program locally everything ok and it runs as 32 bit app. But when I try to run app through IEExec it throws System.BadImageFormatException and shutdown. The problem is that when I load web page in IE and click on the link that point to my app it tries to launch app with command:

c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\IEExec.exe “url_to_my_app“

and looks like IEExec loads CLR 64 bit. I can solve this problem by running:

corflags.exe /32BIT+ /Force c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\IEExec.exe

but I don’t think it’s good idea. Is there any other way to bring IEExec.exe to load CLR 32 bit?

P.S. My app is compiled in anycpu release mode.



I am developing one pos application in .net 3.5 and my application interacting with printer epson TM-U220D .


But when my app starts it gives following messages 

System.BadImageFormatException was unhandledMessage="An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)"
       at jp.co.epson.upos.pntr.init.Verifiability.GetRandomData1(Int32 iSeed, Int32 iSize, Byte[] abyResponse)
       at jp.co.epson.upos.pntr.init.Verifiability.CheckPattern(Int32 iEncodePattern, Int32 iSeed, String strResponse)
       at jp.co.epson.upos.pntr.init.T88IV_Initialization.CheckEPSONDevice()
       at jp.co.epson.upos.pntr.init.AbstractPrinterInitialization.InitializeCommon()
       at jp.co.epson.upos.pntr.init.AbstractPrinterInitialization.Initialize()
       at jp.co.epson.upos.pntr.init.AbstractPrinterInitialization.Initialize(Int32 iResetCounter)
       at jp.co.epson.upos.pntr.init.InitializationThread.ThreadProcess()
       at jp.co.epson.uposcommon.util.EpsonCommonThread.Run()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

System.BadImageFormatException was unhandled


Vinay Khanna


Hi  all,

I am getting "System.BadImageFormatException Could not load file or Assemblies or its dependencies" (Intellitrace log when deployed a azure service)

I have a DLL which i have referenced in my web role, and set its copy local = true. This DLL is build as Any CPU.

Am i missing anything?

Please help.

Vinayak Bhosale.


We are facing problem while migrating a .Net 2.0 application 64 Bit OS Windows Server 2003.
The error is  as below:

"is not a valid Win32 application. (Exception from HRESULT: 0x800700C1) "

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.BadImageFormatException: is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)

the application is running fine on 32 Bit OS windows Server 2003.

Can any one provide any possible soution to the above problem.



System.BadImageFormatException: Could not load file or assembly 'LMSLib' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

Just made a conversion. Updated web.config 
System.BadImageFormatException: Could not load file or assembly 'AssemblyName' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.

How to figure out what actual dependent assembly cause the trouble?




First off: THANK YOU for releasing this incredible project!  I'm totally excited to put this to use.  I think you guys have really done a superior job in answering this most complex problem in application development.

Secondly, I appear to be getting the following exception when trying to run the CTP samples:

An unhandled exception of type 'System.BadImageFormatException' occurred in WinAppSample.exe

Additional information: Could not load file or assembly 'System.Data.Entity, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. An attempt was made to load a program with an incorrect format.

Funny thing is, the version of System.Data.Entity is v2.0.50727, not

I'm running this on 2003 Server 64-bit.  I think that might be the culprit... not sure though. :)

Just wanted to throw this out there and see if there's anything obvious I'm missing...

Thanks, and keep up the amazing work!


I've done a fair amount of digging on this and have found this post that suggests that its caused by the .dll being marked for AMD and not for ia64.  This error occurred after I linked the new cluster to the existing sharepoint farm prior to migration.  Then started moving project files over and rebuilding for the upcoming new server name.  I've tried copying the .dll from the regular 12 hive into the GAC but it won't make a change to the processor architecture.

Do I need to re-run the configuration wizard or something?  Anyone have an easy fix?  Thanks.

Hi Guys.
Hopefully you can help me again this time.

I have serious problems with my projects in Visual Studio 2008.
Last week I got a new PC with Windows 7 64bit, before I was working with XP 32bit.
Visual Studio 2008 and SQL Server 2005 is still the same on both PCs and the project was developed in VS2008.
So I copy everything over to the new 64bit PC. No problems.
I installed all patches, Service Packs, so the Win7 PC has the latest software on it.
I also checked every reference in my project, everything seems to be fine.
Compiling my large projects is working, even it is running fine on every 32bit PC  (target system for the software is  XP embedded 32bit). I tested this multiple times.
I got serious problems if I try to run the compiled software on my Win7 PC or even to debug it in Visual Studio.
I think debugging the project while developing is essential and this is not working anymore.
This is absolutely not working , neither under "any CPU" nor under "x86" settings.
I also checked the framework settings (I am using NetFramwork 2.0 and 3.5). looks ok.
While debugging at the beginning it shows the error message.
Error message:
System.BadImageFormatException occurred
  Message=Could not load file or assembly 'file:///C:\projects\TRUNK\project1\bin\Debug\startingproject.dll' or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.
  FileName=file:///C:\projects\TRUNK\project1\bin\Debug\startingproject.dll   FusionLog==== Pre-bind state information ===
Calling assembly : (Unknown).

Same error message if I try to start the application on the W7 PC. I click the exe-file = same error message.
If I change the corflags to 32bit+ in the assembly themself and start it then, it is also working on my 64bit System. But (of course) this has no effect on the debug mode of VS.
The dependency Walker shows my two missing dlls, which is bogus , cause the dlls doesnt belong to my projects (gpsvc.dll and one from the internet explorer).
Why he is showing this files looks like a mysterie. I found severell threads in the internet about this topic.

Does anybody have any idea to check which assembly or dependency could be fault for the error?
Any suggestions how to check the dependencies or what to take core of in my case changing to work with a 64bit system?

Thanks a lot in advance.


I am currently working on web application project. My project contains three tiers.

Client->intermediate (proxy) ->web service.


Proxy-web application (aspx)

Web service-Indigo web service (SVC)

Visual studio 2005

Client sends request to proxy. It gets the details and calls appropriate method and return result to client.

My problem is I have posted the requested to proxy, it initiated corresponding web method. Before getting the result from web method client connection was closed(time period closed).so in proxy no active object, at that time web method return the result and try to collect the result in proxy code it gives “System.ExcecutionEngineException” was thrown. How to overcome this situation? I want to use response time period in client.

There is no presentation layer in the proxy. It has only codebehind and Class files that used to consume each web method from web service

Thanks in advance for any help


Hi, I have this problem with correctly implementing the memcpy or memmove functions, i get this error when i do.

error C2664: 'memcpy' : cannot convert parameter 1 from 'System::Byte ^' to 'void *' No user-defined-conversion operator available, or Cannot convert a managed type to an unmanaged type

Does any one know where i am going wrong or what to do to eliminate this problem, i would be very grateful if you could help me, thanks.

the code that is causing the errors is pasted below:

void Utility::ImageEventHandler(char^ idSensor, unsigned int width, unsigned int height, unsigned char^ rawImage, int res)
	// Copying aquired image
  memcpy(_raw.img, rawImage, width*height);
	_raw.height = height; 
	_raw.width = width;
	_raw.Res = res;
	isThereAnImage = true;

	// Signaling that an image event occurred.
	WriteEvent(Convert::ToString(idSensor), GR_IMAGE);

	// display fingerprint image
	PrintBiometricDisplay(false, GR_DEFAULT_CONTEXT);

	// now we have a fingerprint, so we can extract template
	_btnExtract->Enabled = true;
	_btnFinish->Enabled = false;



Hello all.

I've struggled with the error "Request for the permission of type System.Web.AspNetHostingPermission failed" twice now and have spent several hours both times trying to solve it.  I'm posting the info I found here in hopes that it will save time for others AND to hopefully get some more recent postings on Google's PageRank.

If you're having the System.Web.AspNetHostingPermission problem, frequently paired with the AJAX Control Toolkit, the fix (at least for me...your results may vary, but I hope they don't) is quite simple.  By now you've probably seen plenty of references to CasPol and how you can run a command to fix your problems.  What those posts tend to leave out are software specs and how exactly to run CasPol.


First, I had this issue on two clients with two different IIS servers.  Both clients were running Visual Studio 2008 (or Visual Web Developer 2008).  One server was running Window Server 2003 (IIS 6) and one was a laptop with Windows 7 64-bit (IIS 7.5).  The problem only occurred after moving the website from the local client to the web server for testing and production.  Visual Studio didn't trust the network share (UNC path) location, so it couldn't compile the website or load the AJAX Control Toolkit properly.

So after trying all sorts of trust configurations, I figured it out.


In order to solve the "Request for the permission of type System.Web.AspNetHostingPermission failed" problem (again, in my case and hopefully in yours), you need to run CasPol on the computer running Visual Studio.  That is, don't run CasPol on the server, but on the client.  The command (at an elevated command prompt, of course) is

C:\Windows\Microsoft.NET\Framework\v2.0.50727\caspol.exe -m -ag 1 -url "file:////\\computername\sharename\*" FullTrust

If you're on a 64-bit system, make sure to ALSO run

Drive:\WINDOWS\Microsoft.NET\Framework64\v2.0.50727\caspol.exe -m -ag 1 -url "file:////\\computername\sharename\*" FullTrust


I really hope that this post helps somebody out.  And that I can find it again when I forget the solution next time I run into this...



In case anyone else runs into this, I found a solution on the ADO.NET forum:


You need to set Properties > Build > Platform target to "x86". This will force it to run in WoW64, so the 32-bit mixed model Phoenix assemblies will load.



Hi Everybody, I have a curious issue with Pex, I get a BadImageFormat exception when running the following parameterized test:

--- Description
failing test: BadImageFormatException, Bad method token.
HeaderConverter.Expression expression;
int i = 0;
expression = this.Parse("?", ref i);

public void ParseThrowsBadImageFormatException676()
    HeaderConverter.Expression expression;
    int i = 0;
    expression = this.Parse("?", ref i);

--- Exception details
System.BadImageFormatException: Bad method token.      at System.Collections.Generic.IEnumerable`1<!!0> System.Linq.Enumerable.Where(System.Collections.Generic.IEnumerable`1<!!0> source, System.Func`2<!!0,System.Boolean> predicate)
    C:\Users\Mike\Documents\Visual Studio 2008\Projects\ConvertAPIHeader\ConvertAPIHeader\HeaderConverter.cs(116): at ConvertAPIHeader.HeaderConverter+Expression ConvertAPIHeader.HeaderConverter+Expression.Parse(System.String text, System.Int32& pos)
    C:\Users\Mike\Documents\Visual Studio 2008\Projects\ConvertAPIHeader\ConvertAPIHeader.Tests03\HeaderConverterExpressionTest.cs(40): at ConvertAPIHeader.HeaderConverter+Expression ConvertAPIHeader.HeaderConverterExpressionTest.Parse(System.String text, System.Int32& pos)

The following code is where the exception occurs:

if (text == null) throw new ArgumentNullException("text");
if (text == string.Empty) throw new ArgumentException("String must not be empty", "text");
if (pos < 0 || pos >= text.Length) throw new ArgumentOutOfRangeException("text", "pos must be within the boundaries of the string");

// This next statement is where the exception is thrown:
Type[] parsableTypes = Assembly.GetExecutingAssembly().GetTypes().Where(i => i.GetCustomAttributes(typeof(ExpressionElementParserAttribute), false).Length > 0).ToArray();

Any ideas, folks? It seems strange to me that according to the exception details the type parameter of IEnumerable is !!0 , I would have expected that to be System.Type.

Thanks in advance for any insight into this oddball problem.


(using VS2008, making a .Net 2.0 WinForm with C#)

I have a 1 project solution, there is a third party DLL that I need to use which has a 32 and a 64 bit version. I was hoping to keep the changes small, so I know I'd have to build a x86 and x64 exe separately but at least the code changes would be small.

I thought at runtime I could just check what OS I had, and then dynamically load the DLL. If I change the reference to the 64bit DLL and make a x64 exe it works, but if I have a reference to the 32bit DLL, but explicitly Assembly.LoadFile the other 64 bit DLL, I can then look at AppDomain.CurrentDomain.GetAssemblies() and see the one I want was loaded, but when it is used I get BadImageFormatException.

I was hoping that could keep the project referencing the 32bit DLL but at runtime load the 64bit DLL. They are different versions but the same culture and public key. To get around the version problem I added to the appconfig a assemblyBinding section

        <assemblyIdentity ... />
        <bindingRedirect oldVersion="" newVersion=""/>

I read somewhere about AppDomain.CurrentDomain.AssemblyResolve and put that in my main() but it wasn't working for me. (hence manually loading the assembly). I also added an AppDomain.CurrentDomain.AssemblyLoad handler to see what was loaded and the desired DLL seemed to be only loaded once before the execption - so what is it checking to determine it is "a bad format?". It is a 64 bit exe and a 64bit DLL (that has the same name & key as the 32bit one that was referenced)


I would have thought there was an easier way to do all of this, am I missing something here?



I am using version 1.4.30707.2 of the Code Contracts library. I am running into a scenario where the following exception message is thrown when I build and run my project with runtime contract checking turned on:

Unhandled Exception: System.BadImageFormatException: 
An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

Everything works fine if I turn off runtime contract checking. It only happens if I build the project with runtime contract checking turned on.

I've boiled the problem down to the following code:

using System.Collections.Generic;
using System.Diagnostics.Contracts;

namespace ConsoleApplication1
  publicclass Item<T> where T : class { }
  publicclass FooItem : Item<FooItem> { }

  publicinterface ITask<T> where T : Item<T>
    void Execute(IEnumerable<T> items);

  internalabstractclass ITaskContract<T> : ITask<T> where T : Item<T>
    void ITask<T>.Execute(IEnumerable<T> items)
      Contract.Requires(items != null);
      Contract.Requires(Contract.ForAll(items, x => x != null));

  publicclass FooTask : ITask<FooItem>
    publicvoid Execute(IEnumerable<FooItem> items) { }

  class Program
    staticvoid Main(string[] args)
      new FooTask();

The problem goes away if I remove the following line of code from the contract class:

Contract.Requires(Contract.ForAll(items, x => x != null));

Am I using Contract.ForAll wrong, or is this a bug in the rewriter?


Hi there,
I am writing a program using C# 3.5. But 8 out of 10 times I got error on one line of code:


BindingFlags.InvokeMethod, null, obj, oParam);

Most of the time, the exception will be

"System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.BadImageFormatException: Invalid access to memory location. (Exception from HRESULT: 0x800703E6)
   --- End of inner exception stack trace ---
   at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
   at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
   at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args)

but once in a while the exception will be:

"System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.OutOfMemoryException: Insufficient memory to continue the execution of the program.
   --- End of inner exception stack trace ---
   at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
   at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
   at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args)

Any idea on why this happened and how to fix it?

BTW, no 64bits OS involved. I called InvokeMemeber for several methods on the same ojject, only one method calling gave exceptions.

Thanks a lot for any help!


I am unable to start my unit tests in debug mode. If I try I get a BadImageFormatException with this message:

Could not load file or assembly 'dbghelp.dll' or one of its dependencies. The module was expected to contain an assembly manifest.

I am running VS2010 Ultimate on a Windows 7 64 bit machine. Debugging works fine for my applications.

How can I start my unit tests in debug mode?



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure