I have following code:
private void askforlocation()
{
if (File.Exists("location.txt"))
{
System.IO.StreamReader loc = new System.IO.StreamReader("location.txt");
string loca = loc.ReadToEnd();
if (loca != "")
{
int index = comboBox1.FindString(loca);
comboBox1.SelectedIndex = index;
}
else
{
label6.Text = "Please select the location!";
}
loc.Close();
}
else label6.Text = "Please select the location!";
}
It is supposed to read value “location” from the file and put it to the combo box, which works ok.
I run this script on Form1_Load.
Now, I have another script:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = comboBox1.SelectedItem.ToString();
System.IO.File.WriteAllText("location.txt", value);
}
This one is supposed to record the choice so that user doesn’t need to enter location every time.
What is happening is when I start a program, so the value is already set, then I try to change it (so that theoretically it should overwrite the previous one), but I get an exception, saying that file is already being used by another process.
I do close the file after I used it. I also tried FILE.DISPOSE.
What am I doing wrong?
I think what’s happening here is that this code:
is causing the
SelectedIndexChangedevent to be raised on the combobox. When that event is raised,comboBox1_SelectedIndexChangedis called, and that method again tries to accesslocation.txt.To fix, I would first change the code in
askforlocationto something like this:since there’s no need to keep the file open for longer than necessary (note that the
usingblock will call theDispose()method on theStreamReaderwhen it exits, which in turn will call theClose()method). After that, I’d consider coming up with a way to keep the event from being fired when you set the selected index on the combobox (maybe use a flag or unwire/rewire the event handler).