c# - 用一种方法打开文件,用另一种方法写入

标签 c# .net file-io

因此,几天来我一直在尝试修复此错误,使用了不同的方法,但似乎没有任何效果。这是我将代码简化为的内容,因此我可以看到出了什么问题。

我首先调用 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,因此您可以使用 ReadAllBytesReadAllText 而不是 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/

相关文章:

c# - 在 C# 中使用 DLL 导入很困难

scala - 为什么 Scala 会在文件中看到更多行?

c# - 如何从 VS 2010 部署安装项目安装到 Windows 7 中的公共(public)目录

java - 创建我自己的基于文本的数据存储

ruby - 如何在文件文本中搜索模式并将其替换为给定值

c# - 为什么C#不像VB那样有Handles子句?

c# - 包含子元素集合的配置元素

c# - 如何为具有多个目标的 CSPROJ 生成 XML 文档

c# - 'Microsoft.ACE.OLEDB.12.0' 提供者未在本地机器上注册

c# - 将 TransactionScope 传递给 Parallel.Invoke 创建的任务