2012-01-20 72 views
1

我需要读取/写入与任何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始终为空。这里是文件内容:

<?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中的条目,当我得到该部分的内容后。 感谢

+0

你有你的解决方案的几个项目?项目中的配置文件是否是您的启动应用程序? – Mharlin

+0

是的,将会有5个项目,其中三个需要访问这个配置文件。 – JimBoone

+0

这是一个与任何exe无关的配置文件。我认为我可以将其用作通用配置平台。应用程序必须从一个主要的exe或运行每个项目的控制台应用程序运行。 – JimBoone

回答

0

可以全球化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; 
      } 
     } 
-2

.NET中的配置文件被运行中的exe文件选择,所以如果你有5个项目(4 DLL的和一个exe文件),并且每个项目都有不同的配置文件,当您将运行在您的应用程序exe文件,由他加载的DLL将认为该exe文件的配置文件是他们的配置文件。

换句话说,要读取dll项目的配置文件,您需要使用他的路径明确打开它。

希望它有助于

+0

好的,所以你说的是我不能使用与exe无关的congif文件 – JimBoone

+0

你可以通过明确地阅读它,你需要用他的完整路径在文件上打开一些xml读取器。 – OopsUser

+0

@OopsUser不正确。 OpenMappedExeConfiguration可以用来覆盖任何路径限制。 – KMoraz