首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

可以从字符串或内存流加载App.Config吗?

可以从字符串或内存流加载App.Config。App.Config是一个常用的配置文件,通常用于存储应用程序的配置信息。在某些情况下,您可能需要从字符串或内存流中加载App.Config,而不是从文件中加载。

以下是一些常见的方法来从字符串或内存流加载App.Config:

  1. 使用XmlReader从字符串或内存流中读取App.Config。
代码语言:csharp
复制
string xml =<configuration><appSettings><add key='key1' value='value1' /></appSettings></configuration>";
XmlReader reader = XmlReader.Create(new StringReader(xml));
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(reader, ConfigurationUserLevel.None);
  1. 使用MemoryStream从字符串或内存流中读取App.Config。
代码语言:csharp
复制
string xml =<configuration><appSettings><add key='key1' value='value1' /></appSettings></configuration>";
byte[] buffer = Encoding.UTF8.GetBytes(xml);
MemoryStream stream = new MemoryStream(buffer);
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = Path.GetTempFileName();
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
config.Save(stream);
  1. 使用XDocument从字符串或内存流中读取App.Config。
代码语言:csharp
复制
string xml =<configuration><appSettings><add key='key1' value='value1' /></appSettings></configuration>";
XDocument doc = XDocument.Parse(xml);
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Clear();
foreach (var element in doc.Descendants("add"))
{
    config.AppSettings.Settings.Add(element.Attribute("key").Value, element.Attribute("value").Value);
}
config.Save();

无论您选择哪种方法,都可以从字符串或内存流中加载App.Config。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券