GVKun编程网logo

c# – 如何写入主exe的.config userSettings部分?(c#编写exe程序)

17

在这篇文章中,我们将带领您了解c#–如何写入主exe的.configuserSettings部分?的全貌,包括c#编写exe程序的相关情况。同时,我们还将为您介绍有关.netCoreAbpSeecon

在这篇文章中,我们将带领您了解c# – 如何写入主exe的.config userSettings部分?的全貌,包括c#编写exe程序的相关情况。同时,我们还将为您介绍有关.net Core Abp See config settings - "CustomSchemaIds" for a workaround、AppSettings In web.config、AppSettings 与 applicationSettings 的优缺点(.NET app.config / Web.config)、AppSettings与applicationSettings的优缺点(.NET app.config/Web.config)的知识,以帮助您更好地理解这个主题。

本文目录一览:

c# – 如何写入主exe的.config userSettings部分?(c#编写exe程序)

c# – 如何写入主exe的.config userSettings部分?(c#编写exe程序)

.NET 2.0中是否有任何支持的API用于写入主exe的.config文件的userSettings部分?

场景是:

Winforms 2.0应用程序.

我有一个具有用户级别范围的设置(数据库连接字符串,如果您需要知道).这意味着当用户保存设置的值时,每个用户都有.net创建的user.config文件.

对于第一次运行应用程序的新用户,应用程序的主exe .config文件在用户设置部分中包含默认值.在项目属性的“设置”选项卡中创建设置时,此部分由visual studio创建.

现在,我想允许计算机中的任何管理员用户能够更改新用户的默认值.只有管​​理员才有此选项,因为普通用户无权写入主exe的.config文件.

我已经找到了如何将用户设置写入用户的.config文件,以及如何写入主.config文件的appSettings部分.但是当我试图找出如何写入主.config的userSettings部分时,我的谷歌搜索失败了

我唯一的机会是失败回System.Xml并在XmlDocument中手动加载.config吗?

解决方法

经过一番研究,我想出了这个解决方案.它有点低级,但仍然可以通过.NET配置API而无需手动解析.config文件.
static void SaveUserSettingDefault(string clientSectionName,string settingName,object settingValue)
{
    System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    // find section group
    ConfigurationSectionGroup group = config.SectionGroups[@"userSettings"];
    if (group == null) return;

    // find client section
    ClientSettingsSection clientSection = group.Sections[clientSectionName] as ClientSettingsSection;
    if (clientSection == null) return;

    // find setting element
    SettingElement settingElement = null;
    foreach (SettingElement s in clientSection.Settings)
    {
        if (s.Name == settingName)
        {
            settingElement = s;
            break;
        }
    }
    if (settingElement == null) return;

    // remove the current value
    clientSection.Settings.Remove(settingElement);

    // change the value
    settingElement.Value.ValueXml.InnerText = settingValue.ToString();

    // add the setting
    clientSection.Settings.Add(settingElement);

    // save changes
    config.Save(ConfigurationSaveMode.Full);
}

给定一个包含以下内容的.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup,System,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089" >
            <section name="MyAssembly.Properties.Settings" type="System.Configuration.ClientSettingsSection,PublicKeyToken=b77a5c561934e089" allowExeDeFinition="MachinetoLocalUser" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <userSettings>
        <MyAssembly.Properties.Settings>
            <setting name="sqlConnectionString" serializeAs="String">
                <value>Server=(local);Database=myDatabase;Integrated Security=true;</value>
            </setting>
        </MyAssembly.Properties.Settings>
    </userSettings>
</configuration>

你会像这样使用它:

if (RunningAsAdmin) // save value in main exe's config file
{
    SaveUserSettingDefault(@"MyAssembly.Properties.Settings",@"sqlConnectionString",theNewConnectionString);
}
else // save setting in user's config file
{
    Settings.Default. sqlConnectionString = theNewConnectionString;
    Settings.Default.Save();
}

.net Core Abp See config settings -

.net Core Abp See config settings - "CustomSchemaIds" for a workaround

Swagger  See config settings - "CustomSchemaIds" for a workaround

 1 System.InvalidOperationException: Conflicting schemaIds: Identical schemaIds detected for types BDtos.ImportExcelSaveDataDto and ADtos.ImportExcelSaveDataDto. See config settings - "CustomSchemaIds" for a workaround
 2    at Swashbuckle.AspNetCore.SwaggerGen.SchemaIdManager.IdFor(Type type)
 3    at Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistry.CreateReferenceSchema(Type type, Queue`1 referencedTypes)
 4    at Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistry.GetOrRegister(Type type)
 5    at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.CreateParameter(ApiDescription apiDescription, ApiParameterDescription apiParameterDescription, ISchemaRegistry schemaRegistry)
 6    at System.Linq.Enumerable.WhereSelectListIterator`2.ToList()
 7    at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
 8    at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.CreateOperation(ApiDescription apiDescription, ISchemaRegistry schemaRegistry)
 9    at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.CreatePathItem(IEnumerable`1 apiDescriptions, ISchemaRegistry schemaRegistry)
10    at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
11    at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.CreatePathItems(IEnumerable`1 apiDescriptions, ISchemaRegistry schemaRegistry)
12    at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GetSwagger(String documentName, String host, String basePath, String[] schemes)
13    at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext)
14    at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
15    at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
16    at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
17    at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
18    at Abp.AspNetZeroCore.Web.Authentication.JwtBearer.JwtTokenMiddleware.<>c__DisplayClass0_0.<<UseJwtTokenMiddleware>b__0>d.MoveNext()
19 --- End of stack trace from previous location where exception was thrown ---
20    at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
21    at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.Invoke(HttpContext context)
22    at Abp.AspNetCore.Security.AbpSecurityHeadersMiddleware.Invoke(HttpContext httpContext) in D:\Github\aspnetboilerplate\src\Abp.AspNetCore\AspNetCore\Security\AbpSecurityHeadersMiddleware.cs:line 26
23    at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.Invoke(HttpContext httpContext)
24    at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)

   主要原因是因为两个类有相同的名称但出现在了不同的全名空间!所以会报错,解决办法如下:

 

AppSettings In web.config

AppSettings In web.config

Posted by scott on 2005年2月13日 

In this article we will review a couple of pratices to keep your runtime configuration information flexible.

ASP.NET provides a configuration system we can use to keep our applications flexible at runtime. In this article we will examine some tips and best practices for using the configuration system for the best results.

The <appSettings> element of a web.config file is a place to store connection strings, server names, file paths, and other miscellaneous settings needed by an application to perform work. The items inside appSettings are items that need to be configurable depending upon the environment, for instance, any database connection strings will change as you move your application from a testing and staging server into production.

As an example, let’s examine this minimal web.config with an appSetting entry to hold our connection string:

 

    1 <?xml version="1.0" encoding="utf-8" ?>

    2 <configuration>  

    3 

    4   <system.web>

    5    <compilation defaultLanguage="c#" debug="true" />

    6  </system.web>

    7 

    8   <appSettings>

    9    <add key="ConnectionInfo" value="server=(local);database=Northwind;Integrated Security=SSPI" />

   10   </appSettings>

   11 

   12 </configuration>

 

To read the key we use the ConfigurationSettings class from the System.Configuration namespace, as shown below.

 

   12 private void Page_Load(object sender, EventArgs e)

   13 {

   14    string connectionInfo = ConfigurationSettings.AppSettings["ConnectionInfo"];

   15    using(SqlConnection connection = new SqlConnection(connectionInfo))

   16    {

   17       connection.Open();

   18 

   19       // perform work with connection

   20 

   21    }        

   22 }

 

Some applications will duplicate these lines of code in many places. If we think about how the above code will evolve over time, we might see a handful of weaknesses. First, we have a hard coded string in place to fetch connection information from the web.config. Hard coded strings can be easy to mistype and difficult to track down if the key ever changes. Secondly, the code will tie us forever to the appSettings section of the web.config file. Although web.config is designed for just such a setting, we might find in the future that we need to pull configuration settings from a database, or change a setting from being application-wide to being a per-user configuration item kept in the Session or in a cookie.

Encapsulation

Let’s abstract away the source of the connection string using a class with a static property.

 

    1 using System.Configuration;

    2 

    3 namespace aspnet.config

    4 {

    5    public class Configuration

    6    {

    7       public static string ConnectionInfo

    8       {

    9          get

   10          {

   11             return ConfigurationSettings.AppSettings["ConnectionInfo"];

   12          }

   13 

   14       }

   15    }

   16 }

 

Now our Page_Load method looks like the following.

 

   11 private void Page_Load(object sender, EventArgs e)

   12 {

   13    using(SqlConnection connection = new SqlConnection(Configuration.ConnectionInfo))

   14    {

   15       connection.Open();

   16 

   17       // perform work with connection

   18 

   19    }        

   20 }

 

The changes we made to the above code were relatively small - but powerful. Now the Page_Load function doesn’t know where the connection string comes from. We could easily change the ConnectionInfo property to retrieve the string from a different source without modifying any other code in the application. We also no longer have to remember the key string and hard code the string at various points in the application. Instead, we can utilize Visual Studio Intellisense when accessing the Configuration class to find the setting we need. The key value only appears once – inside the ConnectionInfo property – so we could again change the key name in the web.config and have only one line of code to update.

Of course this approach only works if all of the code in the application goes to the Configuration class instead of directly to web.config to retrieve settings. For each appSetting entry added to web.config we would add a corresponding property to the Configuration class.

Another advantage to this approach becomes apparent if we have an application setting that is not a string, but a date, integer, or other primitive type. In this case we could have the corresponding Configuration property parse the string from the web.config file and return the appropriate type.

You’ll notice we provided a read-only property for ConnectionInfo. The web.config file is not designed for constant updates. When an ASP.NET application launches a watch is put on the web.config file. ASP.NET will detect if the web.config changes while the application is running. When ASP.NET detects a change it will spin up a new version of the application with the new settings in effect. Any in process information, such as data kept in Session, Application, and Cache will be lost (assuming session state is InProc and not using a state server or database).

Next, let’s take a look at a little known feature of appSettings that can give us even more flexibility.

 

Multiple File Configuration

 

The appSettings element may contain a file attribute that points to an external file. Let’s change our web.config to look like the following.

 

    1 <?xml version="1.0" encoding="utf-8" ?>

    2 <configuration>  

    3   <system.web>

    4    <compilation defaultLanguage="c#" debug="true" />

    5  </system.web>

    6 

    7   <appSettings file="testlabsettings.config"/>

    8 

    9 </configuration>

 

Next, we can create the external file ‘testlabsettings.config’ and add an appSettings section with our connection information.

 

    1 <appSettings>

    2    <add key="ConnectionInfo" value="server=(local);database=Northwind;Integrated Security=SSPI" />

    3 </appSettings>

 

If the external file is present, ASP.NET will combine the appSettings values from web.config with those in the external file. If a key/value pair is present in both files, ASP.NET will use the value from the external file.

The feature demonstrated above is useful when you keep user-specific or environment-specific settings in the external file. Let web.config contain those settings that are global to all the installed instances of your application, while each user or installed site contains their own settings in an external file. This approach makes it easier to move around global web.config changes and keep web.config checked into source control, while each developer can get their own settings separate.

One caveat to this approach is that the ASP.NET runtime does not detect when the external file changes. You’ll need to make changes to web.config itself for ASP.NET to launch a new version of the application with all changes in effect.

I hope this article has given you some tips on using the appSettings section with the maximum amount of flexibility. To see the source code to additional best practices for configuration handling, download the Enterprise Library.

版权声明:本文为博主原创文章,未经博主允许不得转载。

AppSettings 与 applicationSettings 的优缺点(.NET app.config / Web.config)

AppSettings 与 applicationSettings 的优缺点(.NET app.config / Web.config)

在开发 .NET Windows 窗体应用程序时,我们可以在这些App.config标签之间进行选择来存储我们的配置值。哪一个更好?

<configuration>

  <!-- Choice 1 -->
  <appSettings>
    <add key="RequestTimeoutInMilliseconds" value="10000"/>
  </appSettings>

  <!-- Choice 2 -->
  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup,System,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c5612342342" >
        <section name="Project1.Properties.Settings" type="System.Configuration.ClientSettingsSection,PublicKeyToken=b77a5c5612342342" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <applicationSettings>
    <Project1.Properties.Settings>
      <setting name="TABLEA" serializeAs="String">
        <value>TABLEA</value>
      </setting>
    </Project1.Properties.Settings>
  </applicationSettings>

</configuration>

AppSettings与applicationSettings的优缺点(.NET app.config/Web.config)

AppSettings与applicationSettings的优缺点(.NET app.config/Web.config)

在开发.NET Windows窗体应用程序时,我们可以在这些App.config标记之间进行选择以存储我们的配置值。哪一个更好?
<configuration>

  <!-- Choice 1 -->
  <appSettings>
    <add key="RequestTimeoutInMilliseconds" value="10000"/>
  </appSettings>

  <!-- Choice 2 -->
  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup,System,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c5612342342" >
        <section name="Project1.Properties.Settings" type="System.Configuration.ClientSettingsSection,PublicKeyToken=b77a5c5612342342" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <applicationSettings>
    <Project1.Properties.Settings>
      <setting name="TABLEA" serializeAs="String">
        <value>TABLEA</value>
      </setting>
    </Project1.Properties.Settings>
  </applicationSettings>

</configuration>

解决方法

基本< appSettings>更容易处理 – 只需打一个< add key =“....”value =“...”/>进入,你就完成了。

缺点是:没有类型检查,例如你不能安全地假设你想要配置的号码确实有一个号码 – 有人可以在该设置中输入一个字符串…..你只需将它作为ConfigurationManager [“(键)”]访问它然后由你决定知道你在做什么。

此外,随着时间的推移,< appSettings>如果您的应用程序的很多部分开始放入那里(记住旧的windows.ini文件?:-)),可能会变得相当复杂和混乱。

如果可以,我宁愿并建议使用您自己的配置部分 – 使用.NET 2.0,它真的变得非常简单,这样,您可以:

> a)在代码中定义配置设置并使其具有类型安全性
并检查
> b)您可以干净地将您的设置与所有人分开
别人的。您也可以重用您的配置代码!

有一系列非常好的文章可以揭开CodeProject上的.NET 2.0配置系统的神秘面纱:

> Unraveling the mysteries of .NET 2.0 configuration
> Decoding the mysteries of .NET 2.0 configuration
> Cracking the mysteries of .NET 2.0 configuration

强烈推荐! Jon Rista在.NET 2.0中解释配置系统方面表现出色。

关于c# – 如何写入主exe的.config userSettings部分?c#编写exe程序的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于.net Core Abp See config settings - "CustomSchemaIds" for a workaround、AppSettings In web.config、AppSettings 与 applicationSettings 的优缺点(.NET app.config / Web.config)、AppSettings与applicationSettings的优缺点(.NET app.config/Web.config)等相关内容,可以在本站寻找。

本文标签: