用一种方法打开文件,用另一种方法写入
本文关键字:方法 文件 另一种 一种 | 更新日期: 2023-09-27 18:08:35
所以我一直在试图修复这个错误几天,用不同的方法,似乎没有工作。下面是我简化的代码,这样我就可以看到哪里出了问题。
我首先调用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());
}
}
}
}
既然你使用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);
问题出在if (File.OpenWrite("test.txt") != null)
行。文件。OpenWrite打开文件进行写入,并返回一个FileStream
。打开文件,然后,当文件仍然打开时,尝试在语句File.WriteAllBytes(currentFile, buffer);
试着这样做:
var writer = File.OpenWrite("test.txt");
using (writer)
{
byte[] buffer = null;
//...
writer.Write(buffer, 0, buffer.Length);
}
你不需要if条件if (File.OpenWrite(currentFile) != null)
这打开了文件,你再次试图打开相同的文件,并使用WriteAllBytes
这段代码有几个问题和潜在的问题,但最直接的问题是WriteAllBytes
不需要调用OpenWrite
当你调用OpenWrite
时,你打开了文件,用返回的文件对象写文件,你不允许任何其他打开文件的尝试,直到它再次关闭。因为你从来没有在它上调用Dispose
,它将保持锁定状态,直到你的程序退出。
与代码无关的问题是,如果结果是OK
,则只处理对话框,而无论如何都应该处理对话框。您应该查看using
语句来处理资源的处置。Dispose需要被调用,即使是一个异常,所以你要么需要在try..finally
中包装使用一次性对象的代码,要么使用using
为你做这件事。