0

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

Edited by TechSupportGeek

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!");
}
2
Contributors
2
Replies
10
Views
4 Years
Discussion Span
Last Post by TechSupportGeek
0

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).

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.