Reputation: 39
I'm new to coding so be nice. I'm trying to open a .ini file in a program, but I keep getting this error when I do so.
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.
My code:
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog o1 = new OpenFileDialog();
o1.Filter = "INI File |*.ini";
if (o1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
INIFile ini = new INIFile(o1.FileName);
string reini = ini.Read ("Profile Settings", "User ID");
int i = int.Parse(reini);
textBox1.Text = i.ToString();
textBox3.Text = i.ToString();
textBox4.Text = i.ToString();
textBox5.Text = i.ToString();
string rechini = ini.Read("Startup", "Check");
if(rechini == "checked")
{
checkBox1.Checked = true;
}
else
{
checkBox1.Checked = false;
}
}
}
}
Then the int i = int.parse(reini);
gets marked in green
Upvotes: 0
Views: 714
Reputation: 626806
User ID is most probably an alphanumeric string. You'd be safer with .TryParse()
in case user ID can be both of alphanumeric and integer types.
int i = -1;
string user_id = string.Empty;
if (!int.TryParse(reini, out i))
{
user_id = reini;
}
if (!String.IsNullOrEmpty(user_id)) // it is an alphanumeric
{
}
else // it is an integer, use i
{
}
UPDATE Since your User ID is a string, just go with a string:
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog o1 = new OpenFileDialog();
o1.Filter = "INI File |*.ini";
if (o1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
INIFile ini = new INIFile(o1.FileName);
string user_id = ini.Read ("Profile Settings", "User ID");
textBox1.Text = user_id;
textBox3.Text = user_id;
textBox4.Text = user_id;
textBox5.Text = user_id;
string rechini = ini.Read("Startup", "Add To Startup");
if(rechini == "checked")
{
checkBox1.Checked = true;
}
else
{
checkBox1.Checked = false;
}
}
}
}
UPDATE2
There is no Check
key in your Startup
INI file section. The code above is updated. There is Add To Startup
, I guess you need this one.
Upvotes: 1
Reputation: 1740
As stribizhev said, in these cases, TryParse is better than Parse.
This is especially true as your User ID is a string of characters - not a number.
Also, 'Startup' 'checked' will always fail because the setting is named 'Add To Startup' (unless you will have another setting named 'checked' that is not in the file you supplied).
So, change to:
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog o1 = new OpenFileDialog();
o1.Filter = "INI File |*.ini";
if (o1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
INIFile ini = new INIFile(o1.FileName);
string reini = ini.Read("Profile Settings", "User ID");
textBox1.Text = reini;
textBox3.Text = reini;
textBox4.Text = reini;
textBox5.Text = reini;
string rechini = ini.Read("Startup", "Add To Startup");
checkBox1.Checked = rechini == "checked";
}
}
Upvotes: 1