我有一个txt文件加载到窗体加载时列表框中。我试图让这个按钮添加到文本文件。它说文件仍然是打开的。有没有一种方法可以使添加到列表框中的文件的路径即使打开也是如此。我不知道如何关闭这个。我被告知它会自动做到这一点。应用程序仍然说文件是打开并显示错误
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");
}
为什么你打开文件句柄到'file2'变量然后从不使用它?你可以处理这个对象,但你似乎甚至不需要它。 – David