Can I use System.Configuration for working with particular config file?
If title is not clear: I want to read to and to write from some specific .xml
configuration file. Is it possible with S开发者_运维问答ystem.Configuration
?
You can, and very easily:
/// <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);
}
As far as I know, this is not possible.
The classes in the namespace only recognize .config
files in the expected locations (app folder, web.config files and linked config files from those).
It is such trouble to rename a file to .config
from .xml
?
Update (following comment):
You can use ConfigSource
in a configuration section to point to a separate file:
<connectionStrings configSourc="myConnectionStrings.config" />
I think u better to have a look at this page
精彩评论