Writing an INI file


Active member
Apr 29, 2005
Programming Experience
I need to store some information in a file and retrieve it.

I have a small program that allows users to choose which database in SQL to open. I need to store the connection string fields. I was planning originally to store them in the registry, but thought it might be better to store them in an INI file instead. That way the user can delete the file and start over if there is a problem.

I need to store the following entries for 2 or more databases:
User ID
Password (I am useing a very basic encryption method)
Initial Catalog
Data Source

Any ideas?

PS: The next step for me is to have this app close after another app is closed.

Most of my my current projects include a ProgramOptions class (or structure, depending on circumstances) that stores values like a database location in private variables exposed through public properties. When the application starts up it checks for the existence of a file called Options.xml in the program folder. If the file exists, an XmlSerializer is used to deserialize the file to a ProgramOptions object. If not, a ProgramOptions object is created with default values.
[color=Blue]Dim[/color] optionsPath [color=Blue]As[/color] [color=Blue]String[/color] = Application.StartupPath + Path.DirectorySeparatorChar + [color=Blue]Me[/color].OPTIONSFILENAME

[color=Blue] If[/color] File.Exists(optionsPath) [color=Blue]Then[/color]
	[color=Blue]Dim[/color] optionsSerialiser [color=Blue]As New[/color] XmlSerializer(GetType(ProgramOptions))
	[color=Blue]Dim[/color] optionsStream [color=Blue]As New[/color] FileStream(optionsPath, FileMode.Open)

	[color=Green]'Deserialise the existing options.[/color]
	[color=Blue]Me[/color].options = optionsSerialiser.Deserialize(optionsStream)
[color=Blue] Else[/color]
	[color=Green]'Load the default options.[/color]
	[color=Blue]Me[/color].options = [color=Blue]New[/color] ProgramOptions
[color=Blue] End If[/color]
When the program exits, an XmlSerializer is used to serialize the ProgramOptions object to a file called Options.xml in the program folder.
[color=Blue]Dim[/color] optionsSerialiser [color=Blue]As New[/color] XmlSerializer([color=Blue]GetType[/color](ProgramOptions))
[color=Blue] Dim[/color] optionsStream [color=Blue]As New[/color] FileStream(Application.StartupPath + Path.DirectorySeparatorChar + [color=Blue]Me[/color].OPTIONSFILENAME, FileMode.Create)

[color=Green] 'Serialise the new options.[/color]
optionsSerialiser.Serialize(optionsStream, newOptions)