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

我发现

ConfigurationSettings.AppSettings.Get("MySetting")

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

我读到我应该使用:

ConfigurationManager.AppSettings["MySetting"]

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

最好的方法是什么?


当前回答

阅读配置:

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

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

保存到配置:

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

其他回答

我可以在。net Core项目中使用以下方法:

步骤:

Create an appsettings.json (format given below) in your project. Next create a configuration class. The format is provided below. I have created a Login() method to show the usage of the Configuration Class. 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); }

右键单击你的类库,从菜单中选择“添加引用”选项。

在. net选项卡中,选择System.Configuration。这将包括系统。将DLL文件配置到项目中。

更新。net Framework 4.5和4.6;以下将不再工作:

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

现在通过Properties访问Setting类:

string keyvalue = Properties.Settings.Default.keyname;

有关更多信息,请参阅管理应用程序设置。

我强烈建议您为这个调用创建一个包装器。类似于ConfigurationReaderService,并使用依赖注入来获取这个类。通过这种方式,您将能够为测试目的隔离这些配置文件。

所以使用ConfigurationManager.AppSettings["something"];建议并返回该值。如果.config文件中没有任何可用的键,您可以使用此方法创建某种默认返回。

我一直试图找到一个解决这个问题的几天了。我可以通过在web中的appsettings标签中添加一个键来解决这个问题。配置文件。这将在使用helper时覆盖.dll文件。

<configuration>
    <appSettings>
        <add key="loginUrl" value="~/RedirectValue.cshtml" />
        <add key="autoFormsAuthentication" value="false"/>
    </appSettings>
</configuration>