我正在使用一个C#类库,该类需要能够从web.config
或app.config
文件中读取设置(取决于DLL是从ASP.NET Web应用程序还是Windows Forms应用程序引用的)。
我发现
ConfigurationSettings.AppSettings.Get("MySetting")
可以,但是该代码已被Microsoft标记为已弃用。
我读过我应该使用:
ConfigurationManager.AppSettings["MySetting"]
但是,C#类库项目中似乎没有System.Configuration.ConfigurationManager
类。
做这个的最好方式是什么?
#1楼
您需要在项目的references文件夹中 添加对System.Configuration
的引用 。
你绝对应该使用ConfigurationManager
在过时的ConfigurationSettings
。
#2楼
您必须将对System.Configuration程序集的引用添加到项目中。
#3楼
右键单击您的类库,然后从菜单中选择“添加引用”选项; 最后,从.NET选项卡中,选择System.Configuration。 这会将System.Configuration dll包含到您的项目中。
#4楼
对于如下所示的示例App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="countoffiles" value="7" />
<add key="logfilelocation" value="abc.txt" />
</appSettings>
</configuration>
您使用以下代码阅读了上述应用设置:
using System.Configuration;
如果还没有引用,则可能还需要在项目中添加对System.Configuration
的引用。 然后,您可以像这样访问这些值:
string configvalue1 = ConfigurationManager.AppSettings["countoffiles"];
string configvalue2 = ConfigurationManager.AppSettings["logfilelocation"];
希望这可以帮助!
#5楼
我强烈建议您为此呼叫创建一个包装器。 类似于ConfigurationReaderService
并使用依赖项注入来获取此类。 这样,您将能够隔离此配置文件以进行测试。
因此,请使用ConfigurationManager.AppSettings["something"];
建议并返回此值。 如果.config文件中没有可用的密钥,则可以使用此方法创建某种默认返回值。
#6楼
几天来,我一直在尝试解决同一问题。 我可以通过在web.config的appsettings标记内添加密钥来解决此问题。 使用帮助程序时,这应覆盖.dll。
<configuration>
<appSettings>
<add key="loginUrl" value="~/RedirectValue.cshtml" />
<add key="autoFormsAuthentication" value="false"/>
</appSettings>
</configuration>
#7楼
您可能正在将App.config文件添加到DLL。 App.Config仅适用于可执行项目,因为所有dll都从正在执行的exe的配置文件中获取配置。
假设您的解决方案中有两个项目:
- SomeDll
- 某某
您的问题可能与您将app.config包含到SomeDLL而不是SomeExe的事实有关。 SomeDll能够从SomeExe项目中读取配置。
#8楼
我有同样的问题,只是这样阅读:
System.Configuration.ConfigurationSettings.AppSettings["MySetting"]
#9楼
尝试这个:
string keyvalue=System.Configuration.ConfigurationManager.AppSettings["keyname"];
在web.config中应该是下一个结构:
<configuration>
<appSettings>
<add key="keyname" value="keyvalue" />
</appSettings>
</configuration>
#10楼
另外,您可以使用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>();
#11楼
框架4.5和4.6的更新; 以下将不再起作用:
string keyvalue=System.Configuration.ConfigurationManager.AppSettings["keyname"];
现在通过属性访问Setting类:
string keyvalue= Properties.Settings.Default.keyname;
有关更多信息,请参见管理应用程序设置 。
#12楼
我总是使用为所有配置值声明的类型安全属性创建IConfig接口。 然后,一个Config实现类包装对System.Configuration的调用。 现在,您所有的System.Configuration调用都集中在一处,因此维护和跟踪正在使用的字段并声明其默认值变得更加容易和整洁。 我编写了一组私有帮助器方法来读取和解析常见的数据类型。
使用IoC框架,您只需将接口传递给类构造函数,就可以在应用程序中的任何位置访问IConfig字段。 然后,您还可以在单元测试中创建IConfig接口的模拟实现,因此您现在可以测试各种配置值和值组合,而无需触摸App.config或Web.config文件。
#13楼
仅出于完整性考虑,还有一个仅适用于Web项目的选项:
System.Web.Configuration.WebConfigurationManager.AppSettings["MySetting"]
这样做的好处是它不需要添加额外的引用,因此对于某些人可能是更可取的。
#14楼
另一个可能的解决方案:
var MyReader = new System.Configuration.AppSettingsReader();
string keyvalue = MyReader.GetValue("keyalue",typeof(string)).ToString();
#15楼
从配置读取:
您需要添加对Config的引用
- 在您的项目上打开“属性”
- 转到“设置”标签
- 添加“名称”和“值”
使用以下代码获取价值:
字符串值= Properties.Settings.Default.keyname;
保存到配置:
Properties.Settings.Default.keyName = value;
Properties.Settings.Default.Save();
#16楼
当我发现通过在System.Configuration上创建包装器类以系统方式访问应用程序设置变量的最佳方法时,如下所示
public class BaseConfiguration
{
protected static object GetAppSetting(Type expectedType, string key)
{
string value = ConfigurationManager.AppSettings.Get(key);
try
{
if (expectedType == typeof(int))
return int.Parse(value);
if (expectedType == typeof(string))
return value;
throw new Exception("Type not supported.");
}
catch (Exception ex)
{
throw new Exception(string.Format("Config key:{0} was expected to be of type {1} but was not.",
key, expectedType), ex);
}
}
}
现在,我们可以使用下面的另一个类通过硬编码名称访问所需的设置变量
public class ConfigurationSettings:BaseConfiguration
{
#region App setting
public static string ApplicationName
{
get { return (string)GetAppSetting(typeof(string), "ApplicationName"); }
}
public static string MailBccAddress
{
get { return (string)GetAppSetting(typeof(string), "MailBccAddress"); }
}
public static string DefaultConnection
{
get { return (string)GetAppSetting(typeof(string), "DefaultConnection"); }
}
#endregion App setting
#region global setting
#endregion global setting
}
#17楼
这是一个示例: App.config
<applicationSettings>
<MyApp.My.MySettings>
<setting name="Printer" serializeAs="String">
<value>1234 </value>
</setting>
</MyApp.My.MySettings>
</applicationSettings>
Dim strPrinterName as string= My.settings.Printer
#18楼
请检查您正在使用的.net版本。 它应该高于4。并且您必须将System.Configuration系统库添加到您的应用程序
#19楼
步骤1:右键单击“引用”选项卡以添加引用。
步骤2:点击“程序集”标签
步骤3:搜索“ System.Configuration”
步骤4:点击OK(确定)。
然后它会工作
string value = System.Configuration.ConfigurationManager.AppSettings["keyname"];
#20楼
您可以在下面的行中使用,在我的情况下,它可以正常工作:
System.Configuration.ConfigurationSettings.AppSettings["yourKeyName"]
您必须注意上面的代码行也是旧版本,并且在新库中已弃用。
#21楼
不需要ConfigurationManager来访问自己的设置
为此,您应该使用
{YourAppName}.Properties.Settings.{settingName}
#22楼
我能够获得以下方法来为.netcore项目工作:
脚步 :
i)在您的项目中创建一个appsettings.json(格式如下)ii)接下来创建一个配置类,格式如下。 iii)我创建了一个Login()方法来显示配置类的用法。
Create appsettings.json in your project with content :
`
{
"Environments": {
"QA": {
"Url": "somevalue",
"Username": "someuser",
"Password": "somepwd"
},
"BrowserConfig": {
"Browser": "Chrome",
"Headless": "true"
},
"EnvironmentSelected": {
"Environment": "QA"
}
}
`
`
public static class Configuration
{
private static IConfiguration _configuration;
static Configuration()
{
var builder = new ConfigurationBuilder()
.AddJsonFile($"appsettings.json");
_configuration = builder.Build();
}
public static Browser GetBrowser()
{
if (_configuration.GetSection("BrowserConfig:Browser").Value == "Firefox")
{
return Browser.Firefox;
}
if (_configuration.GetSection("BrowserConfig:Browser").Value == "Edge")
{
return Browser.Edge;
}
if (_configuration.GetSection("BrowserConfig:Browser").Value == "IE")
{
return Browser.InternetExplorer;
}
return Browser.Chrome;
}
public static bool IsHeadless()
{
return _configuration.GetSection("BrowserConfig:Headless").Value == "true";
}
public static string GetEnvironment()
{
return _configuration.GetSection("EnvironmentSelected")["Environment"];
}
public static IConfigurationSection EnvironmentInfo()
{
var env = GetEnvironment();
return _configuration.GetSection($@"Environments:{env}");
}
}
`
`
public void Login()
{
var environment = Configuration.EnvironmentInfo();
Email.SendKeys(environment["username"]);
Password.SendKeys(environment["password"]);
WaitForElementToBeClickableAndClick(_driver, SignIn);
}
`
#23楼
我正在使用它,对我来说效果很好:
textBox1.Text = ConfigurationManager.AppSettings["Name"];
#24楼
web.config
与Web应用程序一起使用。 默认情况下, web.config
具有Web应用程序所需的几种配置。 您可以为Web应用程序下的每个文件夹创建一个web.config
文件。
app.config
用于Windows应用程序。 在vs.net中构建应用程序时,它将自动重命名为<appname>.exe.config
并且此文件必须与应用程序一起提供。
您可以使用相同的方法从两个配置文件中调用app settings
值:
System.Configuration.ConfigurationSettings.AppSettings["Key"]