2011-05-22 63 views

回答

2

你可以很容易地:

/// <summary> 
/// Gets any configuration file configuration file object. 
/// </summary> 
/// <param name="path">Path to configuration file.</param> 
/// <param name="createIfNotExist">If true will create new configuration file if is doesn't exist.</param> 
/// <returns>Configuration file object.</returns> 
public static Configuration GetFileConfig(string path, bool createIfNotExist) 
{ 
     if (!File.Exists(path)) 
     { 
       if (createIfNotExist) 
       { 
         using (XmlTextWriter xml = new XmlTextWriter(path, null)) 
         { 
           xml.WriteStartDocument(); 
           xml.WriteStartElement("configuration"); 
           xml.WriteStartElement("appSettings"); 
           xml.WriteEndElement(); 
           xml.WriteStartElement("connectionStrings"); 
           xml.WriteEndElement(); 
           xml.WriteEndElement(); 
           xml.WriteEndDocument(); 
         } 
       } 
       else 
       { 
         throw new ArgumentException("Path doesn't exist", "path"); 
       } 
     } 

     ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap { ExeConfigFilename = path }; 

     return ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); 
} 
+0

我没有看到我在这里指定了样本中的任何**具体**路径。 – zerkms 2011-05-22 06:24:52

+0

更新时,路径在ExeConfigurationFileMap的对象初始值设定项中。 – 2011-05-22 06:25:50

1

据我所知,这是不可能的。

名称空间中的类仅在预期位置(应用程序文件夹,web.config文件和链接的配置文件)中识别.config文件。

.xml将文件重命名为.config有这样的麻烦吗?

更新(以下注释):

可以使用ConfigSource在配置部分以指向一个单独的文件:

<connectionStrings configSourc="myConnectionStrings.config" /> 
+0

当然这是n OT。我只想将应用程序设置存储在某个特定的预定义目录中(让它们成为'.config'文件),我找不到指定该文件完整路径的方式。 – zerkms 2011-05-22 06:16:06

+0

@zerkms - 看看['ConfigSource'](http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource.aspx) - 这应该做你想做的。 – Oded 2011-05-22 06:17:17

+0

@Oded:如果我现在没有'app.config'文件(虽然它是WPF应用程序),并且该文件的路径是“当前用户的基于AppData目录的路径”,该怎么办? – zerkms 2011-05-22 06:20:00

0

我觉得你最好看看this页面

+0

来自链接:'此API支持.NET Framework基础结构,不能直接在您的代码中使用.'该类也被标记为“密封”,因此不能被继承... – Oded 2011-05-22 06:16:14

相关问题