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

发布于 2024-12-04 14:03:40 字数 1706 浏览 0 评论 0原文

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

我首先调用 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());
            }
        }
    }
}

So I've been trying to fix this bug for days, with different methods and nothing seems to work. Here is what I've simplified my code down to, so I can see what is going wrong.

I am calling the open() method first to open the file, read it out to my variable. I am then invoking save() and writing back to the same file.

Yet I get an error saying

The process cannot access the file {$FILE} because it is being used by another process

Is there a solution for this?

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());
            }
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

我只土不豪 2024-12-11 14:03:40

由于您使用 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);

Since you use WriteAllBytes, you could use ReadAllBytes or ReadAllText instead of 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);

素食主义者 2024-12-11 14:03:40

问题出在 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);
        }

The problem lies in the line if (File.OpenWrite("test.txt") != null). File.OpenWrite opens the file for writing and returns a FileStream. You're opening the file, then, while the file is still open, attempting to write to the file in the statement File.WriteAllBytes(currentFile, buffer);

Try something along these lines:

        var writer = File.OpenWrite("test.txt");
        using (writer)
        {
            byte[] buffer = null;
            //...
            writer.Write(buffer, 0, buffer.Length);
        }
鹿港巷口少年归 2024-12-11 14:03:40

您不需要 if 条件 if (File.OpenWrite(currentFile) != null)

这会打开文件,并且您再次尝试打开同一个文件并使用 WriteAllBytes 写入 t0

you dont need the if condition if (File.OpenWrite(currentFile) != null)

This opens the file and again you are trying to open the same file and write t0 it using WriteAllBytes

撧情箌佬 2024-12-11 14:03:40

代码存在几个问题和潜在问题,但最直接的一个是 WriteAllBytes 不需要调用 OpenWrite

当您调用 OpenWrite 时,您打开了用于使用返回的文件对象进行写入的文件,并且您不允许任何其他尝试打开该文件,直到再次关闭该文件。由于您从未对其调用Dispose,因此它将保持锁定状态,直到您的程序退出。

与代码无关的问题是,只有在结果为 OK 时才处理对话框,而无论如何都应该处理对话框。您应该查看 using 语句来处理资源的处置。即使出现异常,也需要调用 Dispose,因此您需要将使用一次性对象的代码包装在 try..finally 中,或者使用 using 来为您完成此操作。

There's several problems and potential problems with the code, but the most immediate one is that WriteAllBytes does not require calling OpenWrite

When you call OpenWrite you opened the file for writing with that file object that's returned and you disallow any other attempts to open the file until it's closed again. Since you never call Dispose on it, it will stay locked until your program exits.

And unrelated issue with the code is that you are only disposing of the dialog if the result is OK when it should always be disposed regardless. You should look into the using statement to handle disposing of resources. Dispose needs to be called even if an exception so you either need to wrap code that uses a disposable object in a try..finally or use using which does that for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文