所以我一直试图用不同的方法修复这个bug几天,似乎什么都没有用。这是我简化了我的代码,所以我可以看到出了什么问题。
我首先调用open()
方法打开文件,将其读取到我的变量中。然后我调用save()
并写回同一个文件。
然而我收到一个错误
该进程无法访问文件{$ FILE},因为它正被另一个进程
使用
有解决方法吗?
private void save()
{
if (currentFile == null)
{
saveAs();
}
else
{
if (File.OpenWrite(currentFile) != null)
{
byte[] buffer = null;
if (currentEncoding == encoding.utf8)
{
buffer = System.Text.Encoding.UTF8.GetBytes(mainTxtBx.Text);
}
else
{
buffer = System.Text.Encoding.ASCII.GetBytes(mainTxtBx.Text);
}
File.WriteAllBytes(currentFile, buffer);
}
}
}
private void open()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = homePath;
openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
currentFile = openFileDialog.FileName.ToString();
openFileDialog.Dispose();
if (File.Exists(currentFile))
{
byte[] buffer = File.ReadAllBytes(currentFile);
if (currentEncoding == encoding.utf8)
{
mainTxtBx.Text = new string(System.Text.Encoding.UTF8.GetChars(buffer).ToArray());
}
else
{
mainTxtBx.Text = new string(System.Text.Encoding.ASCII.GetChars(buffer).ToArray());
}
}
}
}
答案 0 :(得分:4)
由于您使用WriteAllBytes
,因此可以使用ReadAllBytes
或ReadAllText
代替OpenWrite
。
byte[] buffer = File.ReadAllBytes(currentFile);
if (currentEncoding == encoding.utf8)
{
buffer = System.Text.Encoding.UTF8.GetBytes(mainTxtBx.Text);
}
else
{
buffer = System.Text.Encoding.ASCII.GetBytes(mainTxtBx.Text);
}
File.WriteAllBytes(currentFile, buffer);
答案 1 :(得分:2)
问题在于if (File.OpenWrite("test.txt") != null)
行。 File.OpenWrite打开文件进行写入并返回FileStream
。您打开文件,然后,当文件仍然打开时,尝试在语句File.WriteAllBytes(currentFile, buffer);
尝试以下几点:
var writer = File.OpenWrite("test.txt");
using (writer)
{
byte[] buffer = null;
//...
writer.Write(buffer, 0, buffer.Length);
}
答案 2 :(得分:1)
你不需要if条件if (File.OpenWrite(currentFile) != null)
这将打开文件并再次尝试打开同一个文件并使用WriteAllBytes写入t0
答案 3 :(得分:1)
代码存在一些问题和潜在问题,但最直接的问题是WriteAllBytes
不需要调用OpenWrite
当您致电OpenWrite
时,您打开了文件以便使用已返回的文件对象进行写入,并且您不允许任何其他尝试打开该文件,直到它再次关闭为止。由于您从未在其上调用Dispose
,因此在程序退出之前它将一直处于锁定状态。
与代码无关的问题是,如果结果为OK
,则只有处理对话框才能始终处置它。您应该查看using
语句来处理资源的处理。即使异常也需要调用Dispose,因此您需要在try..finally
中包含使用一次性对象的代码,或者使用using
为您执行此操作。