- Практическое руководство. Добавление файла конфигурации приложения в проект C# How to: Add an application configuration file to a C# project
- Добавление файла конфигурации приложения в проект C# To add an application configuration file to a C# project
- Общие сведения о параметрах приложений Application Settings Overview
- Что такое параметры приложения What Are Application Settings
- Ограничения параметров приложения Limitations of Application Settings
- Начало работы с параметрами приложения Getting Started with Application Settings
- App configuration
- Configuration sources
- appsettings.json format and access
- User secrets
- Environment variables
- Command-line arguments
- The return of web.config
- Read configuration in the app
- Strongly typed configuration
Практическое руководство. Добавление файла конфигурации приложения в проект C# How to: Add an application configuration file to a C# project
Добавив файл конфигурации приложения (файл app.config) в проект C#, вы можете настроить способ, которым общеязыковая среда выполнения будет находить и загружать файлы сборки. By adding an application configuration file (app.config file) to a C# project, you can customize how the common language runtime locates and loads assembly files. Дополнительные сведения о файлах конфигурации приложения см. в статье Обнаружение сборок в среде выполнения (.NET Framework). For more information about application configuration files, see How the runtime locates assemblies (.NET Framework).
Приложения UWP не содержат файл app.config. UWP apps don’t contain an app.config file.
При сборке проекта среда разработки автоматически копирует файл app.config, изменяет имя копии файла в соответствии с исполняемым файлом, а затем перемещает копию в каталог bin. When you build your project, the development environment automatically copies your app.config file, changes the file name of the copy to match your executable, and then moves the copy to the bin directory.
Добавление файла конфигурации приложения в проект C# To add an application configuration file to a C# project
В строке меню выберите Проект > Добавить новый элемент. On the menu bar, choose Project > Add New Item.
Откроется диалоговое окно Добавление нового элемента. The Add New Item dialog box appears.
Разверните пункт Установленные > Элементы Visual C# , а затем выберите шаблон Файл конфигурации приложения. Expand Installed > Visual C# Items, and then choose the Application Configuration File template.
В текстовом поле Имя введите имя и нажмите кнопку Добавить. In the Name text box, enter a name, and then choose the Add button.
Общие сведения о параметрах приложений Application Settings Overview
В этой статье описывается, как создавать и хранить данные параметров от имени приложения и пользователей. This article discusses how to create and store settings data on behalf of your application and your users.
Параметры приложения в Windows Forms позволяют легко создавать, хранить и поддерживать настраиваемые приложения и параметры пользователей на клиентском компьютере. The Application Settings feature of Windows Forms makes it easy to create, store, and maintain custom application and user preferences on the client computer. С помощью параметров приложения Windows Forms можно хранить не только данные приложения, например строки подключений к базам данных, но и пользовательские данные, такие как предпочтения пользователя приложения. With Windows Forms application settings, you can store not only application data such as database connection strings, but also user-specific data, such as user application preferences. Используя Visual Studio или настраиваемый управляемый код, можно создавать новые параметры, читать их и записывать на диск, связывать их со свойствами в формах и проверять данные параметров до загрузки и сохранения. Using Visual Studio or custom managed code, you can create new settings, read them from and write them to disk, bind them to properties on your forms, and validate settings data prior to loading and saving.
Параметры приложения позволяют разработчикам сохранять состояние в своем приложении с помощью очень небольшого объема пользовательского кода и заменяют динамические свойства в предыдущих версиях .NET Framework. Application settings enables developers to save state in their application using very little custom code, and is a replacement for dynamic properties in previous versions of the .NET Framework. Параметры приложения содержат много улучшений по сравнению с динамическими свойствами, которые доступны только для чтения. Кроме того, в динамических свойствах используется позднее связывание, и для них требуется дополнительное программирование. Application settings contains many improvements over dynamic properties, which are read-only, late-bound, and require more custom programming. Классы динамических свойств были сохранены в .NET Framework 2,0, но они просто являются классами оболочки, которые тонко заключают классы параметров приложения. The dynamic property classes have been retained in .NET Framework 2.0, but they are just shell classes that thinly wrap the application settings classes.
Что такое параметры приложения What Are Application Settings
Приложениям Windows Forms часто требуются данные, которые крайне важны для запуска приложения, но вы не хотите включать их непосредственно в код приложения. Your Windows Forms applications will often require data that’s critical to running the application, but which you don’t want to include directly in the application’s code. Если приложение использует веб-службу или сервер базы данных, эту информацию можно сохранить в отдельном файле, чтобы их можно было изменить в будущем без повторной компиляции. If your application uses a Web Service or a database server, you may want to store this information in a separate file, so that you can change it in the future without recompiling. Аналогичным образом приложению может потребоваться сохранить данные, относящиеся к текущему пользователю. Similarly, your applications may require storing data that is specific to the current user. В большинстве приложений, например, применяются пользовательские предпочтения, определяющие внешний вид и поведение приложения. Most applications, for example, have user preferences that customize the application’s appearance and behavior.
Параметры приложения отвечают обеим потребностям, предоставляя простой способ хранения параметров приложения и пользователей на клиентском компьютере. Application settings addresses both needs by providing an easy way to store both application-scoped and user-scoped settings on the client computer. С помощью Visual Studio или редактора кода можно определить значение параметра, указав его имя, тип данных и область действия (приложение или пользователь). Using Visual Studio or a code editor, you define a setting for a given property by specifying its name, data type, and scope (application or user). Вы можете даже поместить связанные параметры в именованные группы для повышения простоты и удобочитаемости кода. You can even place related settings into named groups for easier use and readability. После определения эти параметры сохраняются и считываются обратно в память автоматически во время выполнения. Once defined, these settings are persisted and read back into memory automatically at run time. Подключаемая архитектура позволяет изменять механизм сохранения, однако по умолчанию используется локальная файловая система. A pluggable architecture enables the persistence mechanism to be changed, but by default, the local file system is used.
Параметры приложения работают путем сохранения данных в формате XML в различных файлах конфигурации (CONFIG-файлах) в зависимости от того, что является областью действия параметра — приложение или пользователь. Application settings works by persisting data as XML to different configuration (.config) files, corresponding to whether the setting is application-scoped or user-scoped. В большинстве случаев параметры приложения доступны только для чтения. Так как они содержат сведения для программы, обычно их не нужно перезаписывать. In most cases, the application-scoped settings are read-only; because they are program information, you will typically not need to overwrite them. Параметры пользователей, напротив, можно и считывать, и записывать во время выполнения, даже если приложение работает в режиме частичного доверия. By contrast, user-scoped settings can be read and written safely at run time, even if your application runs under partial trust. Дополнительные сведения о частичном доверии см. в разделе Security in Windows Forms Overview. For more information about partial trust, see Security in Windows Forms Overview.
Пользовательские элементы управления могут сохранять собственные параметры с помощью реализации интерфейса IPersistComponentSettings , который предоставляет метод SaveSettings . Custom controls can also save their own settings by implementing the IPersistComponentSettings interface, which exposes the SaveSettings method. Элемент управления ToolStrip Windows Forms реализует этот интерфейс, чтобы сохранить положение панелей инструментов и их элементов между сеансами приложения. The Windows Forms ToolStrip control implements this interface to save the position of toolbars and toolbar items between application sessions. Дополнительные сведения о пользовательских элементах управления и параметрах приложения см. в разделе Application Settings for Custom Controls. For more information about custom controls and application settings, see Application Settings for Custom Controls.
Ограничения параметров приложения Limitations of Application Settings
Нельзя использовать параметры приложения в неуправляемом приложении, где размещается .NET Framework. You cannot use application settings in an unmanaged application that hosts the .NET Framework. Параметры не будут работать в таких средах, как надстройки Visual Studio, C++ для Microsoft Office, элементы управления, размещенные в Internet Explorer, или надстройки и проекты Microsoft Outlook. Settings will not work in such environments as Visual Studio add-ins, C++ for Microsoft Office, control hosting in Internet Explorer, or Microsoft Outlook add-ins and projects.
В настоящее время нельзя выполнить привязку к некоторым свойствам в Windows Forms. You currently cannot bind to some properties in Windows Forms. Наиболее важным примером является свойство ClientSize , так как привязка к этому свойству вызовет непредсказуемое поведение во время выполнения. The most notable example is the ClientSize property, as binding to this property would cause unpredictable behavior at run time. Как правило, такого рода проблем можно избежать путем программного сохранения и загрузки этих параметров. You can usually work around these issues by saving and loading these settings programmatically.
Параметры приложения не имеют встроенных средств для автоматического шифрования информации. Application settings has no built-in facility for encrypting information automatically. Никогда не следует хранить конфиденциальные данные, такие как пароли к базам данных, в виде открытого текста. You should never store security-related information, such as database passwords, in clear text. Если требуется хранить такие сведения, то разработчик приложения обязан обеспечить надлежащую безопасность хранения. If you want to store such sensitive information, you as the application developer are responsible for making sure it is secure. Если нужно хранить строки подключений, рекомендуется использовать встроенную систему безопасности Windows и не прибегать к таким средствам, как жесткое программирование паролей в URL-адресах. If you want to store connection strings, we recommend that you use Windows Integrated Security and not resort to hard-coding passwords into the URL. Для получения дополнительной информации см. Code Access Security and ADO.NET. For more information, see Code Access Security and ADO.NET.
Начало работы с параметрами приложения Getting Started with Application Settings
Если используется Visual Studio, вы можете определить параметры в конструкторе Windows Forms с помощью свойства (ApplicationSettings) в окне Свойства . If you use Visual Studio, you can define settings within the Windows Forms Designer using the (ApplicationSettings) property in the Properties window. При определении параметров таким образом Visual Studio автоматически создает настраиваемый управляемый класс-оболочку, связывающий каждый параметр со свойством класса. When you define settings this way, Visual Studio automatically creates a custom managed wrapper class that associates each setting with a class property. Visual Studio также обеспечивает привязку параметра к свойству в форме или элементе управления таким образом, чтобы параметры элемента управления автоматически восстанавливались при отображении содержащей его формы и автоматически сохранялись при закрытии формы. Visual Studio also takes care of binding the setting to a property on a form or control so that the control’s settings are restored automatically when its form is displayed, and saved automatically when the form is closed.
Если требуется более детальное управление параметрами, можно определить собственный класс-оболочку параметров приложения. If you want more detailed control over your settings, you can define your own custom applications settings wrapper class. Для этого нужно создать класс, производный от ApplicationSettingsBase, добавить свойства, соответствующие каждому параметру, и применить к ним специальные атрибуты. This is accomplished by deriving a class from ApplicationSettingsBase, adding a property that corresponds to each setting, and applying special attributes to these properties. Дополнительные сведения о создании классов-оболочек см. в разделе Application Settings Architecture. For details about creating wrapper classes, see Application Settings Architecture.
Вы можете также использовать класс Binding для программной привязки параметров к свойствам в формах и элементах управления. You can also use the Binding class to bind settings programmatically to properties on forms and controls.
App configuration
The primary way to load app configuration in Web Forms is with entries in the web.config file—either on the server or a related configuration file referenced by web.config. You can use the static ConfigurationManager object to interact with app settings, data repository connection strings, and other extended configuration providers that are added into the app. It’s typical to see interactions with app configuration as seen in the following code:
With ASP.NET Core and server-side Blazor, the web.config file MAY be present if your app is hosted on a Windows IIS server. However, there’s no ConfigurationManager interaction with this configuration, and you can receive more structured app configuration from other sources. Let’s take a look at how configuration is gathered and how you can still access configuration information from a web.config file.
Configuration sources
ASP.NET Core recognizes there are many configuration sources you may want to use for your app. The framework attempts to offer you the best of these features by default. Configuration is read and aggregated from these various sources by ASP.NET Core. Later loaded values for the same configuration key take precedence over earlier values.
ASP.NET Core was designed to be cloud-aware and to make the configuration of apps easier for both operators and developers. ASP.NET Core is environment-aware and knows if it’s running in your Production or Development environment. The environment indicator is set in the ASPNETCORE_ENVIRONMENT system environment variable. If no value is configured, the app defaults to running in the Production environment.
Your app can trigger and add configuration from several sources based on the environment’s name. By default, the configuration is loaded from the following resources in the order listed:
- appsettings.json file, if present
- appsettings.
.json file, if present - User secrets file on disk, if present
- Environment variables
- Command-line arguments
appsettings.json format and access
The appsettings.json file can be hierarchical with values structured like the following JSON:
When presented with the preceding JSON, the configuration system flattens child values and references their fully qualified hierarchical paths. A colon ( : ) character separates each property in the hierarchy. For example, the configuration key section1:key0 accesses the section1 object literal’s key0 value.
User secrets
User secrets are:
- Configuration values that are stored in a JSON file on the developer’s workstation, outside of the app development folder.
- Only loaded when running in the Development environment.
- Associated with a specific app.
- Managed with the .NET CLI’s user-secrets command.
Configure your app for secrets storage by executing the user-secrets command:
The preceding command adds a UserSecretsId element to the project file. The element contains a GUID, which is used to associate secrets with the app. You can then define a secret with the set command. For example:
The preceding command makes the Parent:ApiKey configuration key available on a developer’s workstation with the value 12345 .
For more information about creating, storing, and managing user secrets, see the Safe storage of app secrets in development in ASP.NET Core document.
Environment variables
The next set of values loaded into your app configuration is the system’s environment variables. All of your system’s environment variable settings are now accessible to you through the configuration API. Hierarchical values are flattened and separated by colon characters when read inside your app. However, some operating systems don’t allow the colon character environment variable names. ASP.NET Core addresses this limitation by converting values that have double-underscores ( __ ) into a colon when they’re accessed. The Parent:ApiKey value from the user secrets section above can be overridden with the environment variable Parent__ApiKey .
Command-line arguments
Configuration can also be provided as command-line arguments when your app is started. Use the double-dash ( — ) or forward-slash ( / ) notation to indicate the name of the configuration value to set and the value to be configured. The syntax resembles the following commands:
The return of web.config
If you’ve deployed your app to Windows on IIS, the web.config file still configures IIS to manage your app. By default, IIS adds a reference to the ASP.NET Core Module (ANCM). ANCM is a native IIS module that hosts your app in place of the Kestrel web server. This web.config section resembles the following XML markup:
App-specific configuration can be defined by nesting an environmentVariables element in the aspNetCore element. The values defined in this section are presented to the ASP.NET Core app as environment variables. The environment variables load appropriately during that segment of app startup.
Read configuration in the app
ASP.NET Core provides app configuration through the IConfiguration interface. This configuration interface should be requested by your Blazor components, Blazor pages, and any other ASP.NET Core-managed class that needs access to configuration. The ASP.NET Core framework will automatically populate this interface with the resolved configuration configured earlier. On a Blazor page or a component’s Razor markup, you can inject the IConfiguration object with an @inject directive at the top of the .razor file like this:
This preceding statement makes the IConfiguration object available as the Configuration variable throughout the rest of the Razor template.
Individual configuration settings can be read by specifying the configuration setting hierarchy sought as an indexer parameter:
You can fetch entire configuration sections by using the GetSection method to retrieve a collection of keys at a specific location with a syntax similar to GetSection(«section1») to retrieve the configuration for section1 from the earlier example.
Strongly typed configuration
With Web Forms, it was possible to create a strongly typed configuration type that inherited from the ConfigurationSection type and associated types. A ConfigurationSection allowed you to configure some business rules and processing for those configuration values.
In ASP.NET Core, you can specify a class hierarchy that will receive the configuration values. These classes:
- Don’t need to inherit from a parent class.
- Should include public properties that match the properties and type references for the configuration structure you wish to capture.
For the earlier appsettings.json sample, you could define the following classes to capture the values:
This class hierarchy can be populated by adding the following line to the Startup.ConfigureServices method:
In the rest of the app, you can add an input parameter to classes or an @inject directive in Razor templates of type IOptions to receive the strongly typed configuration settings. The IOptions .Value property will yield the MyConfig value populated from the configuration settings.