如何在C#控制台程序中读取配置文件中的信息?

如何在C#控制台程序中读取配置文件中的信息?,第1张

给个例子你:

配置文件App.config如下:

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

<configuration>

<appSettings>

<add key="InvariantInfo" value="true"/>

</appSettings>

</configuration>

使用

if (ConfigurationManager.AppSettings["InvariantInfo"] != "false")

{

}

绝对没问题的,我都取过N遍了,不行你把你的配置文件删除了,再到VS里面添加一个app.config文件,把内容复制过来

我是用的VS,用CSC编译可能是少了参数了你

我想如果我提供一个对这些文件的快速入门会对大家有些帮助。 在本文章中,许多 C# 源码例子都假设你的项目已经引用了 System.Configuration.dll 和引用了下面的命名空间: using System.Configuration这是使用ConfigurationManager类所必须的,而这个类提供了一种使用配置信息的方法。 Why The .NET framework provides a rich set of classes, and techniques, to simplify application configuration. Essentially, all of these classes make it easy to read and write that configuration information from an XML configuration file. The configuration file includes a number of standard sections, some custom sections for common .NET features, and also allows the developer to create their own custom configuration sections. The standard sections have evolved over time. Initially, standard configuration was done mostly through theappSettingssection, which contains name / value pairs for each setting. Over time, transparent, type-safe support was provided via a generated C#Settingsclass and the correspondingapplicationSettingsanduserSettingsconfiguration sections. 译者信息为什么NET框架提供了一套丰富的类和技术,以简化应用配置。从本质上讲,所有这些类可以很容易地从XML配置文件的读取和写入,配置信息。配置文件包含了.net程序中的一些标准的以及自定义的节点,并且也允许开发者创建自己的配置节点。标准节点随着时间跟以前比有了很大的改变。最开始的时候,标准节点主要是配置应用程序的配置内容,比如为一个属性一个属性或者一个值。随着时间的推移,它也为类型安全提供了支持,同时可以生成C#标准的配置信息以及用户自定义的配置信息

Where Where do I find the configuration file? This is a deceptively complicated problem. Since configuration is hierarchical, there are actually multiple configuration files that may affect an application. These include the machine configuration file, the application (or web) configuration file, the user local settings file, and the user roaming settings file. Machine Configuration The machine configuration file lives with the, not so easily found, .NET framework files. The location of the configuration file is dependent on the version of .NET and type of platform (e.g. 64 bit) used by your application. A typical example, might be: C:\Windows\Microsoft.NET\Framework\v4.0.30319\CONFIG\machine.config In your C# application code, the following will return the location of the file: System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() + @"CONFIG\machine.config"译者信息

何处 我从哪里找到配置文件?这是一个迷惑性的复杂问题。自从配置文件分层后,有多个配置文件可能影响一个应用程序。这包括机器的配置文件,应用程序(或者网页)配置文件,用户本地设置文件,用户的Roaming设置文件。 机器配置 和.NET框架文件一起的机器配置文件,并不是很容易找到。配置文件的位置还取决于.NET的版本和应用程序使用的平台(比如,64位) 一个典型的例子就是

C:\Windows\Microsoft.NET\Framework\v4.0.30319\CONFIG\machine.config 在你的C#应用程序代码中,下面的语句将会返回文件的位置: System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() + @"CONFIG\machine.config" Application Configuration The application configuration file usually lives in the same directory as your application. For web applications, it is named Web.config. For non-web applications, it starts life with the name of App.config. Following a build, it is copied to the same name as your .exe file. So, for the program MyProgram.exe, you might expect to find MyProgram.exe.config, in the same directory. In your C# application code, the following will return the location of the file: AppDomain.CurrentDomain.SetupInformation.ConfigurationFile While it is not generally recommended, you may find that some applications alter the location of the application configuration file as follows: AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", "NewName.config")译者信息

应用配置文件

应用程序配置文件一般跟你的应用程序存在于相同的目录下面。对于web应用程序来说,它的名字是Web.config,而对一般的应用程序来说,它的名字是App.config。在一个项目下,它的名字格式与你的.exe文件相似。比如你的工程名字是MyProgram.exe,那么你就可以在相同的路径下找到MyProgram.exe.config。 在你的C#应用程序源代码中,使用下面的代码可以返回文件的路径: AppDomain.CurrentDomain.SetupInformation.ConfigurationFile 如果它不是被经常调用,你可以做在应用程序的配置文件中做一些小的修改。下面是例子: AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", "NewName.config") User Settings The user settings are almost impossible to find, perhaps by design. The names of the directories vary with versions of Windows. To complicate matters further, the parent folder is generally hidden. The folder structure also incorporates the company name (of the application vendor), the application name, a unique identity for the application, and the application version. An example, on Windows 7, for local user settings might look like: C:\Users\MyUsername\AppData\Local\CompanyName\MyProgram.exe_Url_pnbmzrpiumd43n0cw05z2h4o23fdxzkn\1.0.0.0\user.config In C#, you can get the base directory for local user settings (first line) or roaming user settings (second line) as follows: Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) In C# (see notes in Overview), you can get the exact file path for local user settings (first line) or roaming user settings (second line) as follows: ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming).FilePath译者信息

用户设置 用户设置大多数时候不好找,这很可能是处于设计的原因。目录的名字因Windows版本而异。更复杂的是父目录通常是隐藏的。. 目录结构加入了公司名称(应用程序的供应商),应用程序名称,应用程序唯一ID号和应用程序的版本。 举个例子,在Windows7下,一个本地用户设置可能像这样: C:\Users\MyUsername\AppData\Local\CompanyName\MyProgram.exe_Url_pnbmzrpiumd43n0cw05z2h4o23fdxzkn\1.0.0.0\user.config 在C#中,你可以获得本地用户设置的基目录(第一行)或者临时用户设置(第二行): Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) 在C#中, (见在概述中的注记),你可以获得本地用户设置的解压文件路径(第一行)或者roaming用户设置(第二行): ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming).FilePath Other Configuration If this isn't all confusing enough, you should be aware of a few other files. There is a root Web.config (located in the same directory as machine.config). Also, sub-directories of a web application may provide additional overrides of inherited settings, via a Web.config specific to that sub-directory. Lastly, IIS provides some of its own configuration. A typical location would be: C:\Windows\System32\inetsrv\ApplicationHost.config How As mentioned earlier, the application configuration file is broken into a number of fairly standard configuration sections. Here, we briefly discuss a few of the most common sections. 译者信息

其它配置 如果这还不够混乱,那你应该知道其它的一些文件了(这个不会翻译)。有个原始的Web.config文件(与machine.config同一个目录下)。此外,子目录下面的Web应用程序可能会通过子目录里面的Web.config重写继承(于父目录的Web.config)的设置。 此外,IIS提供了一些自己的配置。一个典型的例子位置在: C:\Windows\System32\inetsrv\ApplicationHost.config 如何 正如前面提到的,应用程序配置文件被分解成若干的相当标准配置部分。在这里,我们简要地讨论一下一些最常见的部分。 appSettings Section The simplest of the standard configuration sections isappSettings, which contains a collection of name / value pairs for each of the settings: <?xml version="1.0" encoding="utf-8" ?><configuration><appSettings><add key="MySetting" value="MySettingValue" /></appSettings></configuration>In C# (see notes in Overview), you can reference the value of a setting as follows: string mySetting = ConfigurationManager.AppSettings["MySetting"]connectionStrings Section Since database connections are so common in .NET, a special section is provided for database connection strings. The section is calledconnectionStrings: <?xml version="1.0" encoding="utf-8" ?><configuration><connectionStrings><add name="MyConnectionStringName" connectionString="Data Source=localhostInitial Catalog=MyDatabaseIntegrated Security=True" providerName="System.Data.SqlClient" /></connectionStrings></configuration>In C#, you can get the connection string as follows: string connectionString = ConfigurationManager.ConnectionStrings[ "MyConnectionStringName"].ConnectionStringInitially, one might wonder at the need to reference aConnectionStringproperty of a "connection string". In truth, the connectionStrings section is poorly named. A better name might have beenconnectionStringSettings, since each entry contains both a connection string and a database provider. The syntax of a connection string is wholly determined by the database provider. In this caseSystem.Data.SqlClient, is the most common database provider for the Microsoft SQL Server database. 译者信息

appSettings 部分 最简单的标准设置部分就是 appSettings 了,这个部分包含了一系列保存配置的 键/值 对。 <?xml version="1.0" encoding="utf-8" ?><configuration><appSettings><add key="MySetting" value="MySettingValue" /></appSettings></configuration>在C#中(见附注概述),你可以通过下面方式引用对应配置的值: string mySetting = ConfigurationManager.AppSettings["MySetting"]connectionStrings 部分 由于数据库连接在.NET中相当普遍,一个特别用于提供数据库连接字符串的部分产生了。这个部分就是 connectionStrings。 <?xml version="1.0" encoding="utf-8" ?><configuration><connectionStrings><add name="MyConnectionStringName" connectionString="Data Source=localhostInitial Catalog=MyDatabaseIntegrated Security=True" providerName="System.Data.SqlClient" /></connectionStrings></configuration>在C# 中,你可以通过下面方式去获取连接字符串: string connectionString = ConfigurationManager.ConnectionStrings[ "MyConnectionStringName"].ConnectionString起初人们可能会奇怪在需要引用一个"connection string"属性作为连接字符串。说实话,这个connectionStrings部分的名字真不恰当。叫做"connectionStringSettings"会更恰当,因为(部分_里面的每个实体够包含了连接字符串和database provider(数据库提供者)。 一个连接字符串的语法完全取决于其database provider。 因此 System.Data.SqlClient 是Microsoft SQL Server最典型的database provider。 applicationSettings and userSettings Section With .NET 2.0, Microsoft tried to make it even easier to use configuration files. They introduced a settings file. A careful observer will note that the "settings" start their life in the application configuration file and, later, get copied to the user settings configuration file. With Windows Form and WPF applications, you'll find a file Settings.settings in the Properties folder of your project. For Console applications, and others, you can also take advantage of settings. Open the Properties for your project, and click on the Settings button/tab. You'll be offered the option of adding a default settings file. Typically, you edit this settings file (or the settings for your project) rather than editing the configuration file directly. The example below is provided only to demonstrate that the settings do actually live in the configuration file. <?xml version="1.0" encoding="utf-8" ?><configuration><configSections><sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"><section name="WinFormConfigTest.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" /></sectionGroup><sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"><section name="WinFormConfigTest.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /></sectionGroup></configSections><userSettings><WinFormConfigTest.Properties.Settings><setting name="MyUserSetting" serializeAs="String"><value>MyUserSettingValue</value></setting></WinFormConfigTest.Properties.Settings></userSettings><applicationSettings><WinFormConfigTest.Properties.Settings><setting name="MyApplicationSetting" serializeAs="String"><value>MyApplicationSettingValue</value></setting></WinFormConfigTest.Properties.Settings></applicationSettings></configuration>To reference one of the settings, you simply use theSettingsclass, which is automatically created for you. A typical reference, might look as follows: string myUserSetting = Properties.Settings.Default.MyUserSettingstring myApplicationSetting = Properties.Settings.Default.MyApplicationSettingNote:Propertiesis a namespace that is automatically created in your application's name space. To change a user's settings, you simply assign a value to the property and save the changes, as follows: Properties.Settings.Default.MyUserSetting = newValueForMyUserSettingProperties.Settings.Default.Save()译者信息

applicationSettings 和 userSettings 部分 在.NET 2.0 中,微软尝试让用户更容易使用设置文件。他们为此引入了设置文件。细心的观察者可能会注意到这些"settings"开始用于应用程序配置文件,并且在后面复制到用于配置文件中。 在Windows Form和WPF程序中,你可以在你的项目的Properties目录下找到一个名为Settings.settings的文件。对于控制台程序还有其它程序,可以通过下面方式使用配置文件。打开你的项目中属性,切换到 设置 选项,你可以通过这里为项目添加一个配置文件。 通常情况下,你可以编辑此设置文件(或者是你的项目设置)来修改配置,而不是直接编辑(.config)配置文件。下面的例子演示了设置在配置文件中如何存储。 <?xml version="1.0" encoding="utf-8" ?><configuration><configSections><sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"><section name="WinFormConfigTest.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" /></sectionGroup><sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"><section name="WinFormConfigTest.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /></sectionGroup></configSections><userSettings><WinFormConfigTest.Properties.Settings><setting name="MyUserSetting" serializeAs="String"><value>MyUserSettingValue</value></setting></WinFormConfigTest.Properties.Settings></userSettings><applicationSettings><WinFormConfigTest.Properties.Settings><setting name="MyApplicationSetting" serializeAs="String"><value>MyApplicationSettingValue</value></setting></WinFormConfigTest.Properties.Settings></applicationSettings></configuration>当你想引用设置的时候,你可以简单的引用Settings类,这个类会自动为你创建。下面是一个典型的引用方式: string myUserSetting = Properties.Settings.Default.MyUserSettingstring myApplicationSetting = Properties.Settings.Default.MyApplicationSetting注意:Properties 命名空间会自动的创建在你的应用程序的命名空间下。 要改变用户设置时,你只需像下面一样为属性赋予一个值然后保存就可以了: Properties.Settings.Default.MyUserSetting = newValueForMyUserSettingProperties.Settings.Default.Save()Upgrading Settings Eventually, you'll want to release a new version of your application. Here, you may encounter a common problem. Since the user settings are version specific, they will be lost following the upgrade. Thankfully, the framework anticipates this requirement and provides theUpgrademethod. A typical way of handling this is to include a booleanUpgradeduser setting, with an initial value of false (when your application is first deployed). So, typical code to handle the upgrade (and retain previous user settings) looks as follows: if (!Properties.Settings.Default.Upgraded) { Properties.Settings.Default.Upgrade()Properties.Settings.Default.Upgraded = trueProperties.Settings.Default.Save()}译者信息

更新设置 实际上,当你想发布一个新版本的程序时,你可能会遇到的一个普遍问题。由于用户设置是有特定版本的,程序升级会导致这些设置丢失。 值得庆幸的是,框架预预料到这种情况并提供了一个更新设置的方法。一个典型的处理办法是引入一个初始值为false的用户设置“Upgraded”(当你首次部署你的程序)。 因此,用来处理升级的典型代码(并保留以前的用户设置)如下所示: if (!Properties.Settings.Default.Upgraded) { Properties.Settings.Default.Upgrade()Properties.Settings.Default.Upgraded = trueProperties.Settings.Default.Save()} What Next In the previous section, you may have noticed the rather verboseconfigSectionssection of the configuration file. This is how Microsoft extended the configuration file to add the new userSettings and applicationSettings sections. It is also how you can add your own custom configuration sections. In a nutshell, you do this by extending theConfigurationSectionandConfigurationElementclasses. Within each of your derived classes, you will be decorating the members with attributes likeConfigurationPropertyAttribute. Simple right? Just kidding. Others have provided excellent descriptions of this slightly complicated, but not too difficult mechanism. I include links at the end of this document for further reading. Here, I only wanted to provide a couple of hints that can get lost in the longer descriptions. 译者信息

下一步做什么 在前一部分,你可能注意到了配置文件相当冗长的configSections。这也是微软如何拓展配置文件,用来添加新的用户设置和应用设置。 它也是你如何来添加你自己定制的配置的区块。 简而言之,你通过拓展 theConfigurationSectionandConfigurationElement类来完成的。在你的每一个继承的类里,你会用类似ConfigurationPropertyAttribute这样的属性来布置你的类成员。 很简单,对吗?开个玩笑。对于其他的,已经提供了很好很详细,稍微有点复杂的描述,和不是很难理解的机制。我会在这篇文档的末尾添加这些链接供进一步阅读。 这里,我只想提供一些在冗长描述中会感到困惑的提示。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/11066582.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-13
下一篇 2023-05-13

发表评论

登录后才能评论

评论列表(0条)

保存