2017-03-03 26 views
0

我有一个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"); 
} 
+2

为什么你打开文件句柄到'file2'变量然后从不使用它?你可以处理这个对象,但你似乎甚至不需要它。 – David

回答

2
StreamWriter file2 = new StreamWriter("Shortcut_Items.txt", true); 
// ... 
File.AppendAllText(path, appendText); 

当然,文件被打开。您创建一个StreamWriter打开该文件进行写入。然后 - 完全独立于StreamWriter - 打开使用File.AppendAllText再次编写的文件。

完全删除您的StreamWriter代码。如果您使用File.AppendAllText,则不需要需要 StreamWriter - File.AppendAllText是自包含的。

1

你永远不会关闭文件。我会推荐'使用'语句,它会自动关闭你的文件。

替换您的这部分代码:

StreamWriter file2 = new StreamWriter("Shortcut_Items.txt", true); 
string path = "Shortcut_Items.txt"; 
string appendText = Environment.NewLine + tempPath + Environment.NewLine; 
File.AppendAllText(path, appendText); 

有了这个:

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); 
+1

为什么使用file2如果你不打算使用它? – LarsTech

+1

如果'StreamWriter'正在锁定文件,那么即使使用此代码,File.AppendAllText仍然会失败,您必须将它移动到'using'之外。 – Quantic

+0

好吧,我更新了我的答案。我假设要求原始问题的人为简洁起见删除了他们的一些代码。 – Curtis

相关问题