Reputation: 27
I am having issues writing to a file in a C# program for class.
My program loads a .txt file to a combo box, which has 3 state options. Users can add up to 5 additional states from a selected list. On Exit, the program saves the added information back to the .txt file if the user chooses Yes.
My issue is that the code below is adding the default states back into the list. Should I be using an If statement under the foreach statement, or is there a way to write it so that only the User-added states are added to my .txt file and not all values all over again?
private void saveMyFile()
{
try
{
StreamWriter outputFile;
outputFile = File.AppendText("states.txt");
foreach (var cbitem in statesComboBox.Items)
{
outputFile.WriteLine(cbitem);
}
outputFile.Close();
MessageBox.Show("Your information has been saved. Closing program.");
}
catch
{
MessageBox.Show("Data could not be written to file");
}
}
Upvotes: 1
Views: 1884
Reputation: 19641
There are several things you can do to achieve this.
If the order of the items in the combobox is fixed, you can skip the first x items when saving:
private int ExistingStates = 3; // You can later change this number when
// loading the items.
private void saveMyFile()
{
StreamWriter outputFile;
outputFile = File.AppendText("states.txt");
foreach (var cbItem in statesComboBox.Items.Cast<string>().Skip(ExistingStates))
{
outputFile.WriteLine(cbItem);
}
outputFile.Close();
}
You can have an array of the existing items so you can check if the item being saved already exists:
private string[] ExistingStates = {"state1", "state2"}; // Add items to the array
// after loading them.
private void saveMyFile()
{
StreamWriter outputFile;
outputFile = File.AppendText("states.txt");
foreach (var cbItem in statesComboBox.Items)
{
if (!ExistingStates.Contains(cbItem))
outputFile.WriteLine(cbItem);
}
outputFile.Close();
}
Another option is to overwrite the existing items by replacing the AppendText
method with CreateText
:
private void saveMyFile()
{
StreamWriter outputFile;
outputFile = File.CreateText("states.txt");
foreach (var cbItem in statesComboBox.Items)
{
outputFile.WriteLine(cbItem);
}
outputFile.Close();
}
Or you can replace the whole method with one simple line (using the WriteAllLines
method):
File.WriteAllLines("states.txt", statesComboBox.Items.Cast<string>());
Hope that helps.
Upvotes: 2