[英]Cannot find my config file
我需要讀取/寫入與任何exe不相關的配置文件。 我正在嘗試:
var appConfiguration = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap() { ExeConfigFilename = "SlamDunkSuper.config" }, ConfigurationUserLevel.None);
if(appConfiguration == null) {
//Configuration file not found, so throw an exception
//TODO: thow an exception here
} else {
//Have Configuration, so work on the contents
var fileEnvironment = appConfiguration.GetSection("fileEnvironment");
}
沒有引發異常,但是fileEnvironment始終為null。 這是文件內容:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="fileEnvironment" type="System.Configuration.NameValueSectionHandler"/>
</configSections>
<fileEnvironment>
<add key="DxStudioLocation" value="123456"/>
</fileEnvironment>
</configuration>
有人請帶我離開曠野。 獲得該部分的內容后,我也不知道如何編寫或更改NameValueCollection中的條目。 謝謝
您可以通過一些小的調整來全球化AppSettingsSection :
<section name="fileEnvironment" type="System.Configuration.AppSettingsSection"/>
消費:
var appConfiguration = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap() { ExeConfigFilename = "SlamDunkSuper.config" }, ConfigurationUserLevel.None);
if (!appConfiguration.HasFile) // no need to null check, ConfigurationManager.OpenMappedExeConfiguration will always return an object or throw ArgumentException
{
//Configuration file not found, so throw an exception
}
else
{
var section = appConfiguration.GetSection("fileEnvironment") as AppSettingsSection;
if (section != null)
{
var dxStudioLocation = section.Settings["DxStudioLocation"].Value;
}
}
在.net中,配置文件由運行中的exe文件選擇,因此,如果您有5個項目(4個dll和一個exe),並且從exe文件運行dll時,每個項目都有一個不同的配置文件。由他加載將認為exe的配置文件是他們的配置文件。
換句話說,要讀取dll項目的配置文件,您需要使用其路徑顯式打開它。
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.