Search code examples
c#powershelldllapp-config.net-assembly

Powershell load custom assembly config file


I have a DLL file, created in visual studio from my c# code. I need to run my code from powershell, therefore I use the Add-Type method to load my assembly.

My Powershell code: Add-Type -Path C:\MyDirectoryWithDllFiles\MyAssembly.dll [MyAssembly.MyClass]::MyStaticMethod()

When I put return "Hello World" in MyStaticMethod, everything works fine.

Of course, my program needs some functionality and a config file was required. I updated my powershell code to this:

[appdomain]::CurrentDomain.SetData("APP_CONFIG_FILE", "C:\MyDirectoryWithDllFiles\MyAssembly.dll.config")
Add-Type -AssemblyName System.Configuration
Add-Type -Path C:\MyDirectoryWithDllFiles\MyAssembly.dll
[MyAssembly.MyClass]::MyStaticMethod()

With the following config file: (MyAssembly.dll.config)

<?xml version="1.0"?>
<configuration>
    <configSections>
        <section name="myCustomSection" type="MyAssembly.MyCustomConfigurationSetting, MyAssembly" />
    </configSections>

    <!--this is the custom config section for myCustomSection-->
    <myCustomSection>
        <!-- some items -->
    </myCustomSection>
</configuration>

In MyStaticMethod I get the items from my config file, and it works fine when I run the code from visual studio. When I run the powershell code, as described above, I get the following error:

PS C:\MyDirectoryWithDllFiles> [MyAssembly.MyClass]::MyStaticMethod() Errors: [System.Configuration.ConfigurationErrorsException: An error occurred creating the configuration section handler for myCustomSection: Could not load file or assembly 'MyAssembly' or one of its dependencies. The system cannot find the file specified. (C:\Users\MyUserName\AppData\Local\Temp\tmp2EB6.tmp line 4) ---> System.IO.FileNotFoundException: Could not load file or assembly 'MyAssembly' or one of its dependencies. The system cannot find the file specified. at System.Configuration.TypeUtil.GetTypeWithReflectionPermission(IInternalConfigHost host, String typeString, Boolean throwOnError)

It tries to find 'MyAssembly', as how I have defined it in the the in the config file. MyAssembly.dll is a dll I have created. But even though I have this line in my powershell it won't work: Add-Type -Path C:\MyDirectoryWithDllFiles\MyAssembly.dll

Any suggestions how I can get this working?


Solution

  • Solution:

    Thanks to JayKul's answer at https://stackoverflow.com/a/23569983/1408786

    I added this to the config section, and now it works fine: Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

    <section name="myCustomSection" type="MyAssembly.MyCustomConfigurationSetting, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />