我正在编写一个c#类库,需要能够从web读取设置。config或app.config文件(取决于DLL是否从ASP. config引用。NET web应用程序或Windows窗体应用程序)。

我发现

ConfigurationSettings.AppSettings.Get("MySetting")

但该代码已被微软标记为弃用。

我读到我应该使用:

ConfigurationManager.AppSettings["MySetting"]

但是,在c#类库项目中,System.Configuration.ConfigurationManager类似乎不可用。

最好的方法是什么?


当前回答

步骤1:右键单击引用选项卡添加引用。

步骤2:单击“程序集”选项卡

第三步:搜索“System”。配置的

步骤4:单击“确定”。

那么它就会起作用。

 string value = System.Configuration.ConfigurationManager.AppSettings["keyname"];

其他回答

此外,您可以使用Formo:

配置:

<appSettings>
    <add key="RetryAttempts" value="5" />
    <add key="ApplicationBuildDate" value="11/4/1999 6:23 AM" />
</appSettings>

代码:

dynamic config = new Configuration();
var retryAttempts1 = config.RetryAttempts;                 // Returns 5 as a string
var retryAttempts2 = config.RetryAttempts(10);             // Returns 5 if found in config, else 10
var retryAttempts3 = config.RetryAttempts(userInput, 10);  // Returns 5 if it exists in config, else userInput if not null, else 10
var appBuildDate = config.ApplicationBuildDate<DateTime>();

试试这个:

string keyvalue = System.Configuration.ConfigurationManager.AppSettings["keyname"];

在网络上。配置文件,这应该是下一个结构:

<configuration>
<appSettings>
<add key="keyname" value="keyvalue" />
</appSettings>
</configuration>

我正在用这个,对我来说效果很好:

textBox1.Text = ConfigurationManager.AppSettings["Name"];

阅读配置:

你需要在配置中添加一个引用:

打开项目上的“属性” 进入“设置”选项卡 添加“名称”和“值” 使用以下代码获取价值: 字符串值= Properties.Settings.Default.keyname;

保存到配置:

   Properties.Settings.Default.keyName = value;
   Properties.Settings.Default.Save();

如果你需要/想要使用ConfigurationManager类…

你可能需要通过微软的NuGet Package Manager加载System.Configuration.ConfigurationManager

工具->NuGet包管理器->管理解决方案的NuGet包…

微软文档

从医生那里有一件事值得注意…

如果应用程序需要对自己的配置进行只读访问, 我们建议你使用GetSection(String)方法。这个方法 提供对当前缓存的配置值的访问 应用程序,其性能优于Configuration 类。