下面的代码在while循环中写入文本文件,有时它会产生一个错误,指出“进程无法访问该文件,因为它正在被另一个进程使用”等等。“ 错误通常发生在“使用(的FileStream FS = File.OpenRead(文件路径))” 有不再被使用的方式来检查文件还是有办法妥善处理文本编写的?什么会导致此代码产生文件锁定错误?
if (File.Exists(filePath))
{
TextWriter sud = File.AppendText(filePath);
sud.WriteLine(GenericLIST[testloop].ToString());
sud.Close();
sud.Dispose();
using (FileStream fs = File.OpenRead(filePath))
{
using (StreamReader sr = new StreamReader(fs))
{
while (!sr.EndOfStream)
{
richTextBox1.AppendText(sr.ReadLine());
}
}
}
}
else
{
TextWriter sud = new StreamWriter(filePath);
sud.WriteLine(GenericLIST[testloop].ToString());
sud.Close();
sud.Dispose();
}
你运行的是哪个版本的Windows? – 2010-08-14 21:37:50
恕我直言,我会简化代码以使用文件(AppendAllText,ReadAllText,WriteAllText)的各种静态方法 - 这比记住使用TextWriter实例更简单,例如:) – 2010-08-14 21:48:55
使用Windows 7并在其上进行测试一台Windows XP Pro机器,它也产生了相同的结果。 明天某个时候会尝试James Manning的建议,看看能否更好的工作 – Mike 2010-08-16 07:56:46