Options file with comments

TechSupportGeek 0 Tallied Votes 141 Views Share

This is a really simple way to maintain an options file for your application in case you don't wanna mess with registry entries, along with added support for comments inside the file. The file will be created at the same location with the executable. In addition, if an error is found or you deleted the file, the program takes appropriate action.

As for the way this will work, it's actually line-by-line. Example file:

# Use '#' to create comments.
# Use '#' as a line separator as well.
# Not everything is an acceptable value.
#
helloWorld=true
string[] defaults = { "# Use '#' to create comments.", "# Use '#' as a line separator as well.", "# Not everything is an acceptable value.", "#", "helloWorld=true" };
bool helloWorld = true;
bool isError = false;

void MainForm_Load(object sender, EventArgs e)
{
	LoadOptions();
	
	if (isError)
	{
		// You could take appropriate action like block the user from editing
		// the options file within the application until the error is solved
		// or exit the application before it loads, altogether.
	}
}

void LoadOptions()
{
	if (!System.IO.File.Exists("Options.txt"))
		System.IO.File.WriteAllLines("Options.txt", default_values);
	
	string[] options = System.IO.File.ReadAllLines("Options.txt");
	foreach (string option in options)
	{
		if (option.StartsWith("#"))
			continue;
				
		string[] split = option.Split('=');
		string name = split[0];
		string val = split[1];
		
		try
		{
			switch (name)
			{
				case "helloWorld":
					helloWorld = bool.Parse(val);
					break;
			}
		}
		catch
		{
			if (isError)
				continue;
			
			MessageBox.Show("One or more errors have been detected in the options file. Delete it so as to solve them.");
			isError = true;
		}
	}
	
	if (helloWorld)
		MessageBox.Show("Hello World!");
}
pritaeas 2,194 ¯\_(ツ)_/¯ Moderator Featured Poster

What reason would I have to use this over the app.config?

TechSupportGeek -3 Junior Poster in Training

Don't really know, to be honest. I just demonstrated an alternative way. Personal preference, I guess. Don't fancy app.config very much (don't ask me why lol).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.