Cоздание файла App.Config c элементом connectionStrings
Cоздание файла App.Config c элементом connectionStrings
Продолжаем работать с приложением, созданным в предыдущей статье. Сегодня повысим гибкость, и переносимость нашего приложения, переместив строку подключения из кода программы в отдельный конфигурационный файл.
Создание и добавление файла App.Config
Чтобы создать конфигурационный файл необходимо выполнить несколько простых действий:
1. Перейдите в окно Solution Explorer
2. Нажмите правую кнопку мыши на имени текущего проекта
3. В появившемся контекстном меню выберите пункт Add, появиться дополнительное подменю, нажмите на пункт New Item.
4. Откроется диалоговое окно со списком шаблонов. Найдите шаблон с именем Application Configuration File, если требуется, измените, имя файла, после чего нажмите на кнопку Add.

В Solution Explorer появится добавленный файл App.Config.

Открываем добавленный файл, щелкнув по нему двойным кликом мыши в окне Solution Explorer.

Файл App.Config это обычный XML файл, внутри которого по умолчанию содержится строка декларации и один корневой элемент configuration. Сам же файл конфигурации, опять же по умолчанию, хранится в папке текущего проекта.

Если вы не знаете, что такое XML и как с ним работать, то прочитайте статью: Введение в язык XML, в которой вкратце изложены все основные моменты.
Создание и добавление элемента connectionStrings
Создадим новый элемент connectionStrings. Для этого сначала введите знак меньше ().

Внутри созданного элемента создадим ещё один элемент с именем add


Для данного элемента добавим несколько атрибутов. Чтобы добавить атрибут нажмите на клавишу пробел после слова add, появится меню авто подстановки.

Выберите атрибут name и нажмите на клавишу Enter

Внутри двойных кавычек укажите любое имя, например MysqlConStr.

Затем добавьте следующий атрибут connectionString

Внутри двойных кавычек нужно указать строку подключения, которая состоит из пары: ключ = значение.
Server указываем ip адрес или имя сервера, где лежит база данных MySQL. Предпочтительнее указывать ip адрес.
Database — имя базы данных;
Uid — пользователь;
Pwd — пароль;
Каждый пара отделяется точкой запятой, а для установки значения используется знак равно.

Строка подключения может содержать множество других ключей, например:
Port по умолчанию MySQL сервер использует порт 3306 и его можно не указывать, но если же по какой-то причине номер порта был изменен, то его следует указать явно.
SslMode если при работе с базой данных вы хотите использовать безопасное соединение с сервером, то укажите для данного параметра одно из следующих значений:
Preferred если сервер поддерживает SSL (криптографический протокол, который обеспечивает безопасность связи) то будет установлено безопасное соединение, если нет, то обычное.
Required все подключения будут только через протокол ssl. Если же на сервере нет поддержки ssl, то при обычном подключении вы получите отказ в подключении к серверу.
Все остальные ключи и их описание можно найти на официальном сайте MySQL.
После добавления строки подключения, добавим ещё один атрибут providerName, который будет хранить имя поставщика данных.

полное содержимое файла App.Config
Таким же образом можно указать любое количество строк подключения и поставщиков данных к разным базам данных: MSSQL, Oracle, Access, например:
Ещё одним преимуществом файлов конфигурации, является быстрое изменение данных, которое не требует перекомпиляции проекта, ведь достаточно всего лишь внести изменения в файл XML, который является отдельным файлом.
Получение данных из файла конфигурации
Конфигурационный файл создан и теперь осталось научиться читать данные из файла App.Config.
Для начала нужно подключить в проект сборку (dll файл) System.Configuration;



2. Чтобы при написании кода обращаться к типам и членам, не используя полных имен, добавьте следующую строку:
В предыдущей статье строка подключения была создана при помощи объекта типа MySqlConnectionStringBuilder (полный исходник здесь)
Удалим весь блок кода, а так же строку
Затем напишем следующий код:
В квадратных скобках указываем значение атрибута name элемента add. В результате в объекте conString мы получаем все значения элементов и атрибутов файла App.Config.
И последнее, что осталось сделать, это передать в объект MySqlConnection созданную строку подключения.
Либо можно сразу же не создавая объект ConnectionStringSettings передать в конструктор класса MySqlConnection конструкцию следующего вида:
8 комментариев
А у меня в этой строке выкидывает какое то исключение. Я пока только обучаюсь и не особо могу понять, что к чему.
Что то ругается именно на ConnectionString в кавычках.
Предупреждение типа NullReferenceException was unhandled
Мало информации… трудно сказать в чём именно проблема.
conString.ConnectionString — это свойство, которое содержит значение connectionString в xml файле App.config
Если выдаёт null, то возможно допущена описка или неверно указано имя элемента в xml файле, либо что-то с его атрибутами.
App.Config in C#

This tutorial will explain the App.Config file in a C# project and demonstrate how it can be used.
Please enable JavaScript
App.Config , or the Application Level Configurations file, is an XML-based file containing the predefined configuration sections available and allows for custom configuration sections that you can modify. It is often automatically generated when creating a new project.
A very basic App.Config can look like this:
As you can see, it only specifies the version of .NET that will be supported during runtime. From here, you can customize how your application locates and loads assembly files. A typical example of what modifications are done to the App.Config would be storing connectionStrings or appSettings to be accessed throughout the entire project.
After setting up the App.Config file the way you want it, you can call its stored values through the ConfigurationManager . To use the ConfigurationManager , you must add the using statement for System.Configuration to your code.
Adding Connection Strings to App.config in C#
To add a connection string, you must ensure that the section for connectionStrings is present. Then within it, you can add the connection string to be used and the provider name, whose value should be the corresponding namespace for its connection string.
To access this connection string in your code, you can use the ConfigurationManager and access the entire ConnectionStrings collection. From there, you can pull the desired connection string by its name.
Adding App Settings to App.config in C#
To add an app setting configuration, you must ensure that the appSettings section is present. Then within it, you can add a new app setting by providing the key it will be called by and its value.
To access this configuration, you can use the ConfigurationManager and access the entire AppSettings collection using the syntax below.
Rafael Martins Cardoso
IT Service Management | SharePoint and Powershell | SQL Server and Oracle Database | Tableau, SAP Business Objects, Microsoft SQL Reporting Services and PowerBI | Business Intelligence | Web services
How to add a configuration file (app.config) to your #C application?

This article shows how to add a simple configuration file (app.config) to your #C project. Sooner or later, you need to change a value such database connection string or username. 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 which means you can create keys to be used on your project without need to recompile it everytime you need to update some value.
What is App.config?
At its simplest, the app.config is an XML file with many predefined configuration sections available and support for custom configuration sections. A “configuration section” is a snippet of XML with a schema meant to store some type of information.
Settings can be configured using built-in configuration sections such as connectionStrings or appSettings. You can add your own custom configuration sections; this is an advanced topic, but very powerful for building strongly-typed configuration files.
Web applications typically have a web.config, while Windows GUI/service applications have an app.config file.
Application-level config files inherit settings from global configuration files, e.g. the machine.config.
Reading from the App.Config
Connection strings have a predefined schema that you can use. Note that this small snippet is actually a valid app.config (or web.config) file:
Once you have defined your app.config, you can read it in code using the ConfigurationManager class. Don’t be intimidated by the verbose MSDN examples; it’s actually quite simple.
The easy way to get data is using dot walking through ConfigurationManager.
In meantime I personally prefer to use a specific class to retrieve my values. For example, if you add a new class file to your project named “InitialDefinition.cs” and write the following:
Once you have done it, you can read data on your main class using the following code:
And voilá. The string connectionType already contains the value “SQL” as specific on “app.config” file.
Writing on the App.Config
Frequently changing the *.config files is usually not a good idea, but it sounds like you only want to perform one-time setup.
See: Change connection string & reload app.config at run time which describes how to update the connectionStrings section of the *.config file at runtime.
Note that ideally you would perform such configuration changes from a simple installer.
How to add App.Config file in Console Application
I want to store the connection string and some parameters in app.config file which we generaly do for windows aplication but I can’t find app.config file for console application. So how should I use this file, how to add this file or there is some other work arroud for the same functionality. I am working in console application
5 Answers 5
Right click on application->Go to Add->you will see the exact picture What i have attached here->Pick the Application Config File.
Well, the other answers might have worked for others, but for me, adding a settings file to the project’s properties solved the problem — it actually serialized the settings (which are editable via a visual designer) to the config file for me. So this way, the config file approach showed in the other answers here didn’t work for me, but instead creating a settings file did work.
Project (not solution) > Add > New Item > Settings File

In addition, you might want to have your settings available in your code with strongly-typed values. I did the following:
- renamed the settings file to something useful — mine was «Settings.settings»
- moved this file to the «Project > Properties» section
- double-clicked the settings file icon
- In the designer, added settings keys and values
- Viola! You have the settings available in your app, with strongly-typed values!
So, now I could access my settings like this (from my console app):
After compilation, I found that these settings are stored automatically in a file named «AssemblyName.exe.config», alongside the console binary itself in the Debug directory.
So, I think this is a cleaner, and more flexible way of creating and managing the app’s config file.
NOTE: Am running Visual Studio Ultimate 2012, and am building a .NET 3.5 console app.