Reputation: 23
I have a txt file that is loaded into a listbox when the form loads. Im trying to get this button to add to the text file. It says the file is still open. Is there a way I can make this add the path of the file selected to the listbox even if open. I'm not sure how to close this. I've been told it automatically does it.
private void shortcutManagerForm_Load(object sender, EventArgs e)
{
if (File.Exists("Shortcut_Items.txt"))
{
shortcutListBox.DataSource = File.ReadAllLines("Shortcut_Items.txt");
}
}
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string tempPath = "";
tempPath = openFileDialog1.FileName;
StreamWriter file2 = new StreamWriter("Shortcut_Items.txt", true);
string path = "Shortcut_Items.txt";
string appendText = Environment.NewLine + tempPath + Environment.NewLine;
File.AppendAllText(path, appendText);
MessageBox.Show("Shortcut added");
}
Upvotes: 0
Views: 47
Reputation: 5892
You are never CLOSING the file. I would recommend the 'using' statement which will automatically close your file for you.
Replace this portion of your code:
StreamWriter file2 = new StreamWriter("Shortcut_Items.txt", true);
string path = "Shortcut_Items.txt";
string appendText = Environment.NewLine + tempPath + Environment.NewLine;
File.AppendAllText(path, appendText);
With this:
using(StreamWriter file2 = new StreamWriter("Shortcut_Items.txt", true))
{
//Do whatever you're going to do with the file
}
string path = "Shortcut_Items.txt";
string appendText = Environment.NewLine + tempPath + Environment.NewLine;
File.AppendAllText(path, appendText);
Upvotes: 1
Reputation: 97708
StreamWriter file2 = new StreamWriter("Shortcut_Items.txt", true);
// ...
File.AppendAllText(path, appendText);
Sure, the file is open. You create a StreamWriter that opens that file for writing. Then - completely independently of that StreamWriter - you open the file for writing again using File.AppendAllText.
Get rid of your StreamWriter code entirely. If you're using File.AppendAllText, you don't need a StreamWriter - File.AppendAllText is self-contained.
Upvotes: 2