Add ConnectionString in Code

January 12, 2013 at 6:06 PMNasif

If you tried to add connection string in code by attempting


you get an exception telling you ConnectionStrings collection is read only.

Here is a way to get past that restriction using reflection:

const string DbConnectionName = "MyConnection";			

if (null == ConfigurationManager.ConnectionStrings[DbConnectionName])
	lock (ConfigurationManager.ConnectionStrings)
		if (null == ConfigurationManager.ConnectionStrings[DbConnectionName])
			//Force ConnectionStrings collection to be writeable
			var field = typeof(ConfigurationElementCollection).GetField("bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
			field.SetValue(ConfigurationManager.ConnectionStrings, false);

			//Create new connection string instance
			var connection = new ConnectionStringSettings();
			connection.Name = DbConnectionName;
			connection.ConnectionString = "Server=myServer;Database=myDb;Uid=myUser;Pwd=myPass;charset=utf8;";
			connection.ProviderName = "MySql.Data.MySqlClient";


In the above example DbConnectionName is a default connection that is expected to be in the ConnectionStrings, if its not there, then we create a new connection string and add it to the ConnectionStrings collection. Lock ensures that the operation is thread-safe. Example shows a MySQL connection string with MySQL provider. Change it to your specific provider and database server.

As for the question, why would anyone want to add connection string in code, when you can do it very easily in app/web.config which is standard best practice (not to mention doing it in code adds hard coded values for db)? Well, it depends to specific need. I have used the above approach in test cases when a database connection in needed while testing compatibility with different types of databases for EntityFramework (for that matter any ORM). I am sure there are many other uses as well.

Posted in: .Net | C#

Tags: , , ,

Parsing INI in .Net : IniFile Class

June 1, 2012 at 12:43 AMNasif

Few days ago I needed INI file parser. One that lets me group standard ini file sections and add/update key-values. After googling quite a bit, the only solution that I found was called "IniFileParser"  from google code. I does work, but throws exception when you have an ini file that has valueless keys. It also seemed quite large (ini parsing should be very simple!)

So, sat down and wrote a simple class that can do the job. Parses ini file, allows easy access of sections and keys with indexer. Total of 200 or so lines (with comments), i.e very small footprint.

You can download the Source from here: (2.63 kb)

Example of Supported INI File Format

;Supported commets are '#' and ';'
#this is also a comment

#following is example of sectionless key value

anotherkey = anothervalue

aKey                =  long            long               value

How to use:

var iniFile = new IniFile();
iniFile["mysection"]["anotherkey"] = "a new value";

//Add a new key and value in a new section
iniFile["myNewSection"]["myNewKey"] = "my new value";

//Add a valueless key
iniFile["mysection"]["ValueLessKey"] = null;

//To check if a key exists (useful for valueless key), use Dictionary.ContainsKey method

//To access/add sectionless key/values use string.Empty as the key
iniFile[string.Empty]["sectionlessKey"] = "a value";

//Retrieve INI content for saving as ini file
File.WriteAllText("myIniFile.ini", iniFile.Ini);

//If you have ini content already, you can pass the content without reloading the file
string iniContent = File.ReadAllText("myIniFile.ini");

//Now create the IniFile instance
var iniFile = new IniFile(iniContent);

Other Specifications:

  • Key and Value must be within the same line. Multi line values are not supported.
  • Removes empty more than 1 lines within a section; allows only 1 empty line per section. Only the first empty line within the section is kept.
  • Only '#' and ';' characters are treated as comments.
  • Allows only "key = value" syntax pattern.
  • Whitespaces in both key and value are disregarded. (2.63 kb)

Posted in:

Tags: , ,