- Configuring Apps by using Configuration Files
- Configuration File Format
- Machine Configuration Files
- Application Configuration Files
- Security Configuration Files
- In This Section
- Практическое руководство. Добавление файла конфигурации приложения в проект C# How to: Add an application configuration file to a C# project
- Добавление файла конфигурации приложения в проект C# To add an application configuration file to a C# project
- Set a value in a Configuration File in a Windows Forms C# Application
- Preliminary step:
- First step:
- Second step
- Other related information:
- Other related links:
- C#, способы хранения настроек программы
- Введение
- C# и app.config
- C# и Properties.Settings
- C# и ini-файлы
Configuring Apps by using Configuration Files
The .NET Framework, through configuration files, gives developers and administrators control and flexibility over the way applications run. Configuration files are XML files that can be changed as needed. An administrator can control which protected resources an application can access, which versions of assemblies an application will use, and where remote applications and objects are located. Developers can put settings in configuration files, eliminating the need to recompile an application every time a setting changes. This section describes what can be configured and why configuring an application might be useful.
Managed code can use the classes in the System.Configuration namespace to read settings from the configuration files, but not to write settings to those files.
This topic describes the syntax of configuration files and provides information about the three types of configuration files: machine, application, and security.
Configuration File Format
Configuration files contain elements, which are logical data structures that set configuration information. Within a configuration file, you use tags to mark the beginning and end of an element. For example, the element consists of child elements . An empty element would be written as or .
As with all XML files, the syntax in configuration files is case-sensitive.
You specify configuration settings using predefined attributes, which are name/value pairs inside an element’s start tag. The following example specifies two attributes ( version and href ) for the element, which specifies where the runtime can locate an assembly (for more information, see Specifying an Assembly’s Location).
Machine Configuration Files
The machine configuration file, Machine.config, contains settings that apply to an entire computer. This file is located in the %runtime install path%\Config directory. Machine.config contains configuration settings for machine-wide assembly binding, built-in remoting channels, and ASP.NET.
The configuration system first looks in the machine configuration file for the element and other configuration sections that a developer might define. It then looks in the application configuration file. To keep the machine configuration file manageable, it is best to put these settings in the application configuration file. However, putting the settings in the machine configuration file can make your system more maintainable. For example, if you have a third-party component that both your client and server application uses, it is easier to put the settings for that component in one place. In this case, the machine configuration file is the appropriate place for the settings, so you don’t have the same settings in two different files.
Deploying an application using XCOPY will not copy the settings in the machine configuration file.
For more information about how the common language runtime uses the machine configuration file for assembly binding, see How the Runtime Locates Assemblies.
Application Configuration Files
An application configuration file contains settings that are specific to an app. This file includes configuration settings that the common language runtime reads (such as assembly binding policy, remoting objects, and so on), and settings that the app can read.
The name and location of the application configuration file depend on the app’s host, which can be one of the following:
These apps have two configuration files: a source configuration file, which is modified by the developer during development, and an output file that is distributed with the app.
When you develop in Visual Studio, place the source configuration file for your app in the project directory and set its Copy To Output Directory property to Copy always or Copy if newer. The name of the configuration file is the name of the app with a .config extension. For example, an app called myApp.exe should have a source configuration file called myApp.exe.config.
Visual Studio automatically copies the source configuration file to the directory where the compiled assembly is placed to create the output configuration file, which is deployed with the app. In some cases, Visual Studio may modify the output configuration file; for more information, see the Redirecting assembly versions at the app level section of the Redirecting Assembly Versions article.
For more information about ASP.NET configuration files, see ASP.NET Configuration Settings.
Internet Explorer-hosted app.
If an app hosted in Internet Explorer has a configuration file, the location of this file is specified in a
tag with the following syntax:
In this tag, location is a URL to the configuration file. This sets the app base. The configuration file must be located on the same website as the app.
Security Configuration Files
Security configuration files contain information about the code group hierarchy and permission sets associated with a policy level. We strongly recommend that you use the Code Access Security Policy tool (Caspol.exe) to modify security policy to ensure that policy changes do not corrupt the security configuration files.
Starting with the .NET Framework 4, the security configuration files are present only if security policy has been changed.
The security configuration files are in the following locations:
Enterprise policy configuration file: %runtime-install-path%\Config\Enterprisesec.config
Machine policy configuration file: %runtime-install-path%\Config\Security.config
User policy configuration file: %USERPROFILE%\Application data\Microsoft\CLR security config\vxx.xx\Security.config
In This Section
How to: Locate Assemblies by Using DEVPATH
Describes how to direct the runtime to use the DEVPATH environment variable when searching for assemblies.
Redirecting Assembly Versions
Describes how to specify the location of an assembly and which version of an assembly to use.
Specifying an Assembly’s Location
Describes how to specify where the runtime should search for an assembly.
Configuring Cryptography Classes
Describes how to map an algorithm name to a cryptography class and an object identifier to a cryptography algorithm.
How to: Create a Publisher Policy
Describes when and how you should add a publisher policy file to specify assembly redirection and code base settings.
Configuration File Schema
Describes the schema hierarchy for startup, runtime, network, and other types of configuration settings.
Практическое руководство. Добавление файла конфигурации приложения в проект 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.
Set a value in a Configuration File in a Windows Forms C# Application
Using Microsoft Visual Studio Community 2019.
How can I set a value (a path) in a Configuration File, so it can be updated and then restart the application with the updated value (without having to recompile the application)?
This is a legacy project that I don’t really know. The most important requirement is to have the capability to change this path without having to recompile the application. This is what I’ve tried so far:
Preliminary step:
To check what kind of project it is. Based on this question, I check that the .csproj file contains:
So, to my understanding the project is a WinForms Application.
Also, I’ve tried to seach for the GUID found in the .csproj file:
But the seach for that GUID gives no result, and also is not listed on this two GUID list:
Note: The core of the question is based the asumption that this project is a WinForms Application. Please let me know if this the wrong way of finding the type of this project, or even better pointing out the right way of doing it.
First step:
To edit the Configuration File, going to the Solution Explorer, in which I cannot find any .config file, but if I check the files of this project (via Windows Explorer), I found a app.config file.
I update this file outside of Visual Studio (I’ll come back to this later), and add a test property. This modification is done following the structure found in the file, no external source to do this modification.
Then, in the code try to get the value:
None of which bring the value stored in the app.config file, in fact all of then brings null .
Then, update the app.config file following this post configuration file in a Windows Forms C# Application
Which didn’t work either.
Second step
Going back to the modification of the app.config , discart this modifications and add a different Configuration File (after all, the app.config is not visible in the Solution Explorer). This consist in adding a new configuration file app1.config following this post related with configuration file in a Windows Forms C# Application and also this one Adding and reading from a Config file.
So after adding the new configuration file, all my apptemps with System.Configuration.ConfigurationManager.AppSettings brings null .
Also, when adding the this new configuration file, if I choose app.config the show me a message saying
A file with the name ‘App.config’ already exits.
So after all, the project is (in some way) finding that file.
Other related information:
In the file Settings.Designer.cs if I add the following:
And then using this line:
Is possible to get the value, but this does not satisfy the requirement that the path can be changed without recompiling the application.
Other related links:
This are other links related with adding a configuration file to Visual Studios projects, I’ve also tried some of this solutions but without obtaining the expected results:
C#, способы хранения настроек программы
Введение
В интернете приведено очень много способов хранения настроек программы, но все они как-то разбросаны, поэтому я решил их собрать вместе и расписать, как этим пользоваться.
C# и app.config
На хабре уже была посвящена этому тема, поэтому… перейти
C# и Properties.Settings
Информация о Properties.Settings
Организация Properties.Settings — это обычный xml файл, который можно найти в папке пользователя:
С:\ Users \ [user name] \ AppData \ Local \ [ (Project Name) or (AssemblyCompany) ] \ [name project_cashBuild] \ [AssemblyVersion] \ user.config
Для начала нам нужно создать такие переменные для Properties.Settings. Перейдем в Properties -> Settings.settings:
Я создал 3-и переменные и выбрал область их использования: 2- область пользователь и 1- приложение.
Различие между областями просты. Область приложения можно только читать, а пользователь — изменять и читать.
Вернемся к переменным:
- Version — версия нашей программы. Определил ее строкой и областью приложение. Т.к. версия может содержать буквы (например, b — от beta). А область выбрал, чтоб не менялась наша версия приложения (т.к. AssemblyVersion редко кто использует).
- Save_text — это переменная, куда мы будем сохранять наш текст.
- open_sum — сколько раз мы открыли программу.
Теперь перейдем к коду
Результаты работы программы
Первый запуск, мы видим, что кол-во запусков равно 1. И теста в richTextBox1 нет.
Теперь напишем и сохраним текст.
При втором запуске мы видим, что текст сохранен, и кол-во запусков уже 2-ва.
Очень удобно использовать этот объект, если надо работать в разных областях видимости в одном проекте. Метод хорош, когда вам не надо, чтоб рядовой пользователь рылся в файлах настройки программы.
C# и ini-файлы
С ini-файлами все на оборот, они лежат в папке рядом с программой, что позволяет пользователю изменить настройки вне-программы. Данный способ хорош, если настройки программы заносятся вручную. Например, эмулятор для запуска игры без лицензии (тотже revLoader).
Теперь перейдем к нашей теме. Для работы с таким типом файлов, нам нужно создать класс по работе с ним. Создаем класс, например «IniFile», подключаем пространство имен, которых нет:
А теперь разбираем по-порядку:
Теперь переходим в основную программу.
Результаты работы программы
При первом запуска, у нас нет файла config.ini. Поэтому при проверке возвращаются fasle и мы приравниваем окно к минимальным параметрам.
Меняем параметры окна и жмем «Применить»
Редактируем файл config.ini руками и жмем загрузить.
На этом все, в следующий раз опишу работу с xml файлами и с бинарными файлами.