Search code examples
c#compiler-errorscscshell32.dll

Referencing Shell32.dll?


I don't have .NET 4.5 to unzip zip files, so I'm using Shell32 like this. But when I reference the dll like this:

csc.exe /r:"C:\Windows\System32\shell32.dll" ...

I get this error:

fatal error CS0009: Metadata file 'c:\Windows\System32\shell32.dll' could not be opened -- 'An attempt was made to load
    a program with an incorrect format. '

Update: Without Visual Studio, just csc.exe.


Solution

  • Shell32 is a COM server that you can use in your C# program. You however have to generate an interop assembly first to convert the type library inside shell32.dll (same idea as .NET metadata) to declarations that the CLR can understand. Either by running Tlbimp.exe or, much simpler, by adding a reference to the DLL in the IDE.

    As long as you do this from the command line and don't use msbuild to get a .csproj project file compiled then you have to do the same thing that msbuild does, run tlbimp. For shell32.dll this only has to be done once and you can check-in the interop library in source control so you don't have to do it again. Use /r on the interop library.

    Using the IDE or MSBuild.exe are of course the wise choices. Also helps you fall in the pit of success, you really want to use the Embed Interop Types feature so you don't need the interop assembly at runtime and don't have to deploy it. Looking at the build commands generated by MSBuild is useful.