Powershell如何加载自定义程序集配置文件?

3

我有一个DLL文件,是从我的C#代码在Visual Studio中创建的。我需要从PowerShell来运行我的代码,因此我使用Add-Type方法来加载程序集。

我的PowerShell代码如下: Add-Type -Path C:\MyDirectoryWithDllFiles\MyAssembly.dll [MyAssembly.MyClass]::MyStaticMethod()

当我在MyStaticMethod中输入返回“Hello World”,一切正常。

当然,我的程序需要一些功能,需要使用配置文件。 我将我的PowerShell代码更新为以下内容:

[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()

以下是配置文件的内容:(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>

在 MyStaticMethod 方法中,我从配置文件中获取条目,在从 Visual Studio 运行代码时可以正常工作。但当我运行 PowerShell 代码时,如上所述,会出现以下错误:
PS C:\MyDirectoryWithDllFiles> [MyAssembly.MyClass]::MyStaticMethod() Errors: [System.Configuration.ConfigurationErrorsException: 在创建 myCustomSection 配置节处理程序时出现错误: 无法加载文件或程序集 'MyAssembly' 或它的某一个依赖项。系统找不到指定的文件。(C:\Users\MyUserName\AppData\Local\Temp\tmp2EB6.tmp 第 4 行) ---> System.IO.FileNotFoundException: 无法加载文件或程序集 'MyAssembly' 或它的某一个依赖项。系统找不到指定的文件。在 System.Configuration.TypeUtil.GetTypeWithReflectionPermission(IInternalConfigHost host, String typeString, Boolean throwOnError)
它试图查找“MyAssembly”,就像我在配置文件中定义的那样。MyAssembly.dll 是我创建的一个 DLL 文件。但是,即使我在 PowerShell 中有这一行也不起作用: Add-Type -Path C:\MyDirectoryWithDllFiles\MyAssembly.dll
有什么建议可以让这个工作起来吗?

我相信PowerShell不会加载MyAssembly.dll.config,因为您的程序集正在被加载到由PowerShell进程创建的应用程序域中。您需要自己加载配置文件 - 可以使用ConfigurationManager.OpenExeConfiguration(MyAssembly.Location)。 - Digvijay
看起来配置文件本身已经被加载了。但是这一行<section name="myCustomSection" type="MyAssembly.MyCustomConfigurationSetting, MyAssembly" /> 寻找 MyAssembly,但无法加载 MyAssembly。 - 1408786user
1
你能试着重新排列一下吗:Add-Type -AssemblyName System.Configuration Add-Type -Path C:\MyDirectoryWithDllFiles\MyAssembly.dll [appdomain]::CurrentDomain.SetData("APP_CONFIG_FILE", "C:\MyDirectoryWithDllFiles\MyAssembly.dll.config") [MyAssembly.MyClass]::MyStaticMethod() - Digvijay
我已按照您提到的顺序重新排列了它。但仍然出现相同的错误。 - 1408786user
1个回答

1

解决方案:

感谢JayKul在https://dev59.com/gW7Xa4cB1Zd3GeqPvOvM#23569983上的回答。

我将以下内容添加到配置部分,现在它可以正常工作了: 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" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接