因此,几天来我一直在尝试修复此错误,使用了不同的方法,但似乎没有任何效果。这是我将代码简化为的内容,因此我可以看到出了什么问题。
我首先调用 open()
方法打开文件,将其读出到我的变量中。然后我调用 save()
并写回同一个文件。
但是我得到一个错误提示
The process cannot access the file {$FILE} because it is being used by another process
有解决办法吗?
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);
关于c# - 用一种方法打开文件,用另一种方法写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7410618/