AppSettings

 1.winform中读写配置文件appSettings 一节中的配置。

 #region 读写配置文件
        /// <summary>
        /// 修改配置文件中某项的值
        /// </summary>
        /// <param name="key">appSettings的key</param>
        /// <param name="value">appSettings的Value</param>
        public static void SetConfig(string key, string value)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            if (config.AppSettings.Settings[key] != null)
                config.AppSettings.Settings[key].Value = value;
            else
                config.AppSettings.Settings.Add(key, value);

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

        /// <summary>
        /// 读取配置文件某项的值
        /// </summary>
        /// <param name="key">appSettings的key</param>
        /// <returns>appSettings的Value</returns>
        public static string GetConfig(string key)
        {
            string _value = string.Empty;
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] != null)
            {
                _value = config.AppSettings.Settings[key].Value;
            }
            return _value;
        }
        #endregion

2.appSettings 元素(常规设置架构)

包含自定义应用程序设置,如文件路径、XML Web services URL 或存储在应用程序的 .ini 文件中的任何信息。

<appSettings
   file="relative file name" >
</appSettings>

 

下面几部分描述了属性、子元素和父元素。

属性
元素说明

file

可选的 String 属性。

指定包含自定义应用程序配置设置的外部文件的相对路径。指定的文件包含的设置类型与在 appSettingsaddclear 和remove 属性中指定的设置类型相同,并且使用的键/值对格式也与这些元素相同。

指定的路径是本地配置文件的相对路径。如果找不到指定的文件,运行库会忽略该属性。

由于 Web.config 文件的任何更改都会导致应用程序重新启动,因此,使用一个单独的文件则既可以让用户修改 appSettings节中的值,又不会导致应用程序重新启动。该单独文件的内容将与 Web.config 文件中的 appSettings 节合并。此功能限于appSettings 属性。

注意   在 .NET Framework 2.0 版中,现在可以在一个单独文件包括所有支持 configSource 属性的配置元素的配置设置。但是,当使用 configSource 属性时,由于没有元素设置的合并,因此您必须将整个节移动到单独文件。使用 configSource 属性时,对 Web.config 文件有一次写入操作。这会导致应用程序重新启动,但是随后对该节的更新会直接写入单独文件,而不会导致后面的应用程序重新启动。有关更多信息,请参见 ConfigSource

子元素
元素说明

add

可选的元素。

向应用程序设置集合添加名称/值对形式的自定义应用程序设置。

clear

可选的元素。

移除所有对继承的自定义应用程序设置的引用,仅允许由当前 add 属性添加的引用。

remove

可选的元素。

从应用程序设置集合中移除对继承的自定义应用程序设置的引用。

父元素
元素说明

configuration

指定公共语言运行库和 .NET Framework 应用程序所使用的每个配置文件中均需要的根元素。

system.web

指定配置文件中 ASP.NET 配置设置的根元素,并且包含各种用于配置 ASP.NET Web 应用程序和控制应用程序的行为方式的配置元素。

 
备注
  appSettings 元素存储自定义应用程序配置信息,如文件路径、XML Web services URL 或存储在应用程序的 .ini 文件中的任何信息。可以使用  ConfigurationSettings 类在代码中访问  appSettings 元素中指定的键/值对。

您可以使用 file 属性指定一个配置文件,该配置文件提供其他设置或重写 appSettings 元素中指定的设置。您可以将 file 属性用于源代码管理组开发方案,例如,当用户需要重写在应用程序配置文件中指定的项目设置时。在 file 属性中指定的配置文件必须将appSettings 元素(而不是 configuration 元素)作为根节点。

在 .NET Framework 2.0 版应用程序中,将数据库连接字符串存储在 connectionStrings 元素(ASP.NET 设置架构)集合中,而不是存储在应用程序设置集合中。

下面的默认 appSettings 元素不是在 Machine.config 文件或根 Web.config 文件中显式配置的。但是,它是应用程序返回的默认配置。

   <appSettings file="">
      <settings>
         <clear />
      </settings>
   </appSettings>
示例
 在  file 属性中指定的配置文件必须将  appSettings 元素(而不是  configuration 元素)作为根节点。

下面的代码示例演示如何使用在 file 属性中指定的配置文件的正确格式。

<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
<add key="Application1" value="MyApplication1" />
<add key="Setting1" value="MySetting" />
</appSettings>

下面的代码示例演示如何在配置文件中定义自定义应用程序设置。

<configuration>
    <appSettings>
        <add key="Application Name" value="MyApplication" />
    </appSettings>
</configuration>
 

配置节处理程序

AppSettingsSection

配置成员

AppSettings

AppSettings

AppSettings

可配置的位置

Machine.config

根级别的 Web.config

应用程序级别的 Web.config

虚拟或物理目录级别的 Web.config

要求

Microsoft Internet 信息服务 (IIS) 5.0、5.1 或 6.0

.NET Framework 版本 1.0、1.1 或 2.0

Microsoft Visual Studio 2003 或 Visual Studio 2005

 

### appsettings.json 文件的作用 `appsettings.json` 是 .NET 应用程序中用于存储应用程序配置信息的标准文件格式。它以 JSON 格式组织数据,便于开发者进行配置管理。该文件通常用于存储应用程序运行时所需的参数,例如数据库连接字符串、日志配置、第三方服务密钥等[^1]。 其主要作用包括: - **集中管理配置**:通过 `appsettings.json` 文件,可以将应用程序的所有配置信息集中存储,避免硬编码在代码中。 - **环境适配**:.NET 支持多环境配置文件,例如 `appsettings.Development.json` 和 `appsettings.Production.json`,从而实现不同环境下的差异化配置。 - **依赖注入支持**:在 .NET 中,可以通过依赖注入机制将配置数据绑定到类中,提升代码的可维护性和测试性。 ### 配置方法 #### 1. 创建 appsettings.json 文件 在项目根目录下创建 `appsettings.json` 文件,并按照 JSON 格式定义配置信息。例如: ```json { "AppSettings": { "ApplicationName": "MyApp", "LoggingLevel": "Information", "ConnectionString": "Server=localhost;Database=MyAppDB;User=sa;Password=Password123;" } } ``` #### 2. 配置文件编码 为了避免中文乱码问题,需要确保 `appsettings.json` 文件的编码格式为 **UTF-8 with BOM(UTF-8 with sign)**。在 Visual Studio 中,可以通过以下方式保存为该编码: - 打开文件后,点击菜单栏的 **工具** → **自定义** → 添加 **高级保存选项**。 - 使用高级保存选项,选择 **UTF-8 with BOM** 格式进行保存[^2]。 #### 3. 读取配置信息 在 .NET 6 中,可以通过 `IConfiguration` 接口读取配置信息。以下是一个示例: ```csharp using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; var builder = WebApplication.CreateBuilder(args); // 读取配置 var configuration = builder.Configuration; // 获取配置值 string appName = configuration["AppSettings:ApplicationName"]; string connectionString = configuration["AppSettings:ConnectionString"]; Console.WriteLine($"Application Name: {appName}"); Console.WriteLine($"Connection String: {connectionString}"); var app = builder.Build(); app.Run(); ``` #### 4. 绑定配置到类 为了更方便地使用配置,可以将配置绑定到一个类上: ```csharp public class AppSettings { public string ApplicationName { get; set; } public string LoggingLevel { get; set; } public string ConnectionString { get; set; } } ``` 在 `Program.cs` 中绑定配置: ```csharp var appSettings = new AppSettings(); configuration.GetSection("AppSettings").Bind(appSettings); Console.WriteLine($"Application Name: {appSettings.ApplicationName}"); ``` #### 5. 多环境配置 为了支持多环境配置,可以创建多个配置文件,例如: - `appsettings.Development.json` - `appsettings.Production.json` 在 `Program.cs` 中,.NET 会根据当前环境自动加载对应的配置文件。 ```csharp var builder = WebApplication.CreateBuilder(new WebApplicationOptions { EnvironmentName = "Development" // 可以动态设置环境 }); ``` #### 6. 依赖注入使用配置 在服务中注入 `IConfiguration`,可以直接使用配置信息: ```csharp public class MyService { private readonly IConfiguration _configuration; public MyService(IConfiguration configuration) { _configuration = configuration; } public void PrintConfig() { var appName = _configuration["AppSettings:ApplicationName"]; Console.WriteLine($"Application Name from service: {appName}"); } } ``` 在 `Program.cs` 中注册服务: ```csharp builder.Services.AddTransient<MyService>(); var app = builder.Build(); var myService = app.Services.GetRequiredService<MyService>(); myService.PrintConfig(); ``` ### 总结 通过 `appsettings.json` 文件,.NET 应用程序可以方便地管理配置信息,并通过 `IConfiguration` 接口灵活地读取和绑定配置。同时,注意文件编码格式以避免中文乱码问题[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值