【发布时间】:2017-09-26 07:26:44
【问题描述】:
我有一个 DLL 文件,它是在 Visual Studio 中使用我的 c# 代码创建的。我需要从 powershell 运行我的代码,因此我使用 Add-Type 方法来加载我的程序集。
我的 Powershell 代码:
Add-Type -Path C:\MyDirectoryWithDllFiles\MyAssembly.dll
[MyAssembly.MyClass]::MyStaticMethod()
当我在 MyStaticMethod 中输入 return "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() 错误:[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 进程创建的 appdomain 中。您需要自己加载配置 - 可能使用 ConfigurationManager.OpenExeConfiguration(MyAssembly.Location);
-
看起来配置文件本身已加载。但随后 行查找 MyAssembly 但无法加载 MyAssembly
-
你可以尝试重新排序: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()
-
我已经按照你提到的顺序重新排序了。但仍然是同样的错误。
标签: c# powershell dll app-config .net-assembly