我正在开发一个 C# 类库,它需要能够从 web.config
或 app.config
文件中读取设置(取决于 DLL 是从 ASP.NET Web 应用程序还是 Windows 窗体应用程序引用的)。
我发现
ConfigurationSettings.AppSettings.Get("MySetting")
有效,但该代码已被 Microsoft 标记为已弃用。
我读过我应该使用:
ConfigurationManager.AppSettings["MySetting"]
但是,C# 类库项目中似乎没有 System.Configuration.ConfigurationManager
类。
做这个的最好方式是什么?
对于如下示例 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"];
您需要在项目的 references 文件夹中添加一个引用到 System.Configuration
。
您绝对应该使用 ConfigurationManager
而不是过时的 ConfigurationSettings
。
.NET Framework 4.5 和 4.6 的更新;以下将不再起作用:
string keyvalue = System.Configuration.ConfigurationManager.AppSettings["keyname"];
现在通过属性访问设置类:
string keyvalue = Properties.Settings.Default.keyname;
有关详细信息,请参阅 Managing Application Settings。
右键单击您的类库,然后从菜单中选择“添加引用”选项。
从 .NET 选项卡中,选择 System.Configuration。这会将 System.Configuration DLL 文件包含到您的项目中。
ConfigurationManager.ConnectionStrings[0].ConnectionString
我正在使用它,它对我很有效:
textBox1.Text = ConfigurationManager.AppSettings["Name"];
从配置中读取:
您需要添加对配置的引用:
在您的项目上打开“属性”转到“设置”选项卡添加“名称”和“值”使用以下代码获取值:字符串值 = Properties.Settings.Default.keyname;
保存到配置:
Properties.Settings.Default.keyName = value;
Properties.Settings.Default.Save();
您必须向项目添加对 System.Configuration 程序集的引用。
您可能会将 App.config 文件添加到 DLL 文件中。 App.Config 仅适用于可执行项目,因为所有 DLL 文件都从正在执行的 EXE 文件的配置文件中获取配置。
假设您的解决方案中有两个项目:
一些DLL
一些Exe
您的问题可能与您将 app.config 文件包含到 SomeDLL 而不是 SomeExe 的事实有关。 SomeDll 能够从 SomeExe 项目中读取配置。
尝试这个:
string keyvalue = System.Configuration.ConfigurationManager.AppSettings["keyname"];
在 web.config 文件中,这应该是下一个结构:
<configuration>
<appSettings>
<add key="keyname" value="keyvalue" />
</appSettings>
</configuration>
第 1 步:右键单击“参考”选项卡以添加参考。
第 2 步:单击“程序集”选项卡
第 3 步:搜索“System.Configuration”
第四步:点击确定。
然后它将起作用。
string value = System.Configuration.ConfigurationManager.AppSettings["keyname"];
我有同样的问题。以这种方式阅读它们:System.Configuration.ConfigurationSettings.AppSettings["MySetting"]
This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings
web.config
用于网络应用程序。 web.config
默认情况下具有 Web 应用程序所需的多项配置。您可以为 Web 应用程序下的每个文件夹创建一个 web.config
。
app.config
用于 Windows 应用程序。当您在 Visual Studio 中构建应用程序时,它会自动重命名为 <appname>.exe.config
,并且此文件必须与您的应用程序一起交付。
您可以使用相同的方法从两个配置文件中调用 app settings
值:System.Configuration.ConfigurationSettings.AppSettings["Key"]
System.Configuration.COnfigurationSettings.AppSettings.Get("Key")
而不是方括号。
正如我找到了以系统方式访问应用程序设置变量的最佳方法,方法是在 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
}
此外,您可以使用 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>();
如果您需要/想要使用 ConfigurationManager
类...
您可能需要由 Microsoft 通过 NuGet 包管理器 加载 System.Configuration.ConfigurationManager
工具->NuGet 包管理器->管理解决方案的 NuGet 包...
文档中值得注意的一件事......
如果您的应用程序需要对其自己的配置进行只读访问,我们建议您使用 GetSection(String) 方法。此方法提供对当前应用程序的缓存配置值的访问,比 Configuration 类具有更好的性能。
我强烈建议您为此调用创建一个 wrapper。类似于 ConfigurationReaderService
并使用 dependency injection 来获取此类。这样,您将能够隔离此配置文件以进行测试。
所以使用建议的 ConfigurationManager.AppSettings["something"];
并返回此值。使用此方法,如果 .config 文件中没有任何可用的键,您可以创建某种默认返回。
app.DEBUG.config
、app.RELEASE.config
和 app.TEST.config
等。
为了完整起见,还有一个仅适用于 Web 项目的选项:System.Web.Configuration.WebConfigurationManager.AppSettings["MySetting"]
这样做的好处是它不需要添加额外的引用,因此对于某些人来说可能更可取。
我总是使用为所有配置值声明的类型安全属性创建一个 IConfig 接口。 Config 实现类然后包装对 System.Configuration 的调用。您的所有 System.Configuration 调用现在都在一个地方,维护和跟踪正在使用的字段并声明它们的默认值变得更加容易和清晰。我编写了一组私有辅助方法来读取和解析常见数据类型。
使用 IoC 框架,您只需将接口传递给类构造函数,即可在应用程序中的任何位置访问 IConfig 字段。然后,您还可以在单元测试中创建 IConfig 接口的模拟实现,因此您现在可以测试各种配置值和值组合,而无需修改 App.config 或 Web.config 文件。
请检查您正在使用的 .NET 版本。它应该高于 4。并且您必须将 System.Configuration 系统库添加到您的应用程序中。
您可以使用以下行。就我而言,它正在工作: System.Configuration.ConfigurationSettings.AppSettings["yourKeyName"]
您必须注意上述代码行也是旧版本,并且在新库中已弃用。
ConfigurationManager 不是您访问自己的设置所需要的。
为此,您应该使用
{YourAppName}.Properties.Settings.{settingName}
我能够使以下方法适用于 .NET Core 项目:
脚步:
在您的项目中创建一个 appsettings.json(格式如下)。接下来创建一个配置类。格式如下。我创建了一个 Login() 方法来显示配置类的用法。在您的项目中创建 appsettings.json 内容:{ "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(); } 公共静态浏览器 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; } 返回浏览器.Chrome; } public static bool IsHeadless() { return _configuration.GetSection("BrowserConfig:Headless").Value == "true"; } 公共静态字符串 GetEnvironment() { return _configuration.GetSection("EnvironmentSelected")["Environment"]; } 公共静态 IConfigurationSection EnvironmentInfo() { var env = GetEnvironment(); return _configuration.GetSection($@"Environments:{env}"); } } public void Login() { var environment = Configuration.EnvironmentInfo(); Email.SendKeys(环境["用户名"]); Password.SendKeys(环境["密码"]); WaitForElementToBeClickableAndClick(_driver, SignIn); }
另一种可能的解决方案:
var MyReader = new System.Configuration.AppSettingsReader();
string keyvalue = MyReader.GetValue("keyalue",typeof(string)).ToString();
几天来,我一直在尝试解决同样的问题。我能够通过在 web.config 文件的 appsettings 标记中添加一个键来解决此问题。这应该在使用帮助程序时覆盖 .dll 文件。
<configuration>
<appSettings>
<add key="loginUrl" value="~/RedirectValue.cshtml" />
<add key="autoFormsAuthentication" value="false"/>
</appSettings>
</configuration>
extra :如果您正在处理类库项目,则必须嵌入 settings.json
文件。
类库实际上不应该直接引用 app.config 中的任何内容——该类没有 app.config,因为它不是应用程序,而是一个类。
转到 JSON 文件的属性。更改构建操作 -> 嵌入式资源。使用下面的代码来阅读它。
var assembly = Assembly.GetExecutingAssembly();
var resourceStream = assembly.GetManifestResourceStream("Assembly.file.json");
string myString = reader.ReadToEnd();
现在我们有了一个 JSON 字符串,我们可以使用 JsonConvert
对其进行反序列化
如果您没有将文件嵌入程序集中,则不能仅使用没有文件的 DLL 文件
这是一个示例: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
不定期副业成功案例分享