进程无法访问文件'...'因为它正由另一个进程使用



可能重复:
打开streamreader时出错,因为文件被另一个进程使用

在C#中,我正试图构建一个程序,将文本文件中列出的一定数量的文件或目录从同一网络上的一台计算机复制到另一台计算机(例如,从"\PC_of_MARK"到"\PC_OFF_SARAH")。然而,在打开和关闭StreamReader后,我似乎无法用streamwriter打开流。

在我能够复制任何东西之前,我需要能够用我的程序编辑"files.txt"的内容。

在我的表单上,我有4个按钮:添加、删除、关闭和复制。我还有一个ListBox lbItems,它包含来自"files.txt"的行。

该程序位于Delete(删除)功能中:为了从"files.txt"中删除一行,我读取了lbItems的内容并将其存储在列表中。接下来,我删除列表中与lbItems中所选项目具有相同索引的字符串。最后,我想通过打开StreamWriter(这是错误发生的地方)并用新的列表覆盖"files.txt"来更新"files.txt"。

"files.txt"包含以下2行:

"%UserProfile%\Documents\files.txt"&"%UserProfile%\Downloads\RubikCube">

public partial class Form1 : Form
{
List<string> envKeys = new List<string>();
List<string> envValues = new List<string>();
public Form1()
{
InitializeComponent();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
IDictionary ev = Environment.GetEnvironmentVariables();
foreach (DictionaryEntry de in ev)
{
envKeys.Add("%" + de.Key.ToString() + "%");
envValues.Add(de.Value.ToString());
}
syncList();
}
private void syncList()
{
StreamReader r = new StreamReader(@"C:UsersEigenaarDocumentsfiles.txt");
string line = r.ReadLine();
while (line != "")
{
lbItems.Items.Add(line);
line = r.ReadLine();
}
r.Close();
}
private void btnRemove_Click(object sender, EventArgs e)
{
if (lbItems.SelectedIndex != -1)
{
if (MessageBox.Show("Ben je zeker dat je " + lbItems.Items[lbItems.SelectedIndex] + " uit de lijst wil verwijderen?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.None) == DialogResult.Yes)
{
List<string> array = new List<string>();
using (StreamReader r = new StreamReader(@"C:UsersEigenaarDocumentsfiles.txt"))
{
string line = r.ReadLine();
while (line != null)
{
array.Add(line);
line = r.ReadLine();
}
string t = r.ReadToEnd();
}
array.RemoveAt(lbItems.SelectedIndex);
//Error occurs here:
using (StreamWriter w = new StreamWriter(@"C:UsersEigenaarDocumentsfiles.txt", false))
//The process cannot access the file 'C:UsersEigenaarDocumentsfiles.txt' because it is being used by another process.
{
foreach (string str in array)
{
w.WriteLine(str);
}
}
lbItems.Items.RemoveAt(lbItems.SelectedIndex);
}
}
} 
}

如果有人知道我在说什么,请帮忙!

我认为您的问题出现在第一个中

using(StreamReader r = new StreamReader(@"C:UsersEigenaarD...

using应该会导致流被丢弃,但这可能不够快地关闭流,我会尝试在第一个using块的末尾添加r.Close()。这样可以确保把手被释放,以便您可以再次打开它。

如果不起作用,您可以尝试将文件作为读取共享打开,这样它就不会被锁定。

相关内容

最新更新