2011-05-22 64 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

相關問題