C#控制台在应用程序退出时删除文件时出现错误。

huangapple go评论76阅读模式
英文:

C# console got error when delete file upon app exit

问题

我有一个C#控制台应用程序,在启动时创建一个文件,在退出时删除该文件。
在第一次运行时,一切正常,但在第二次运行时,在删除时出现了一个错误,提示“无法访问文件,因为它正在被其他进程使用”。
这是我的代码:

internal class Program
{
    static string path => $"E:/abc.txt";
    static void Main(string[] args)
    {
        if (!File.Exists(path)) File.Create(path);
        AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
        {
            if (File.Exists(path)) File.Delete(path);
        };
        while (true) { }
    }
}
英文:

I have a C# console app that create a file when begin and delete that file when exit.
In the first run, it's ok, but in the second run, it got an error like "cannot access file because it's used by other process" when delete.
This is my code:

internal class Program
{
    static string path => $"E:/abc.txt";
    static void Main(string[] args)
    {
        if (!File.Exists(path)) File.Create(path);
        AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
        {
            if (File.Exists(path)) File.Delete(path);
        };
        while (true) { }
    }
}

答案1

得分: 1

我建议更换进程间通信的方法,.NET 提供了多种进程间通信的方式,包括消息队列、REST API、命名/匿名管道、内存映射文件等,还有一些我在这里没有提到的方式。

如果只是单向通信在单台计算机上(一个进程仅写入,另一个仅读取),最简单的方式可能是使用匿名管道。如果是双向通信,或者涉及到网络通信,你可以使用命名管道内存映射文件,或者选择更强大的解决方案,如使用消息队列。

英文:

Well, I would suggest replacing that method of inter-process communication to another method - dot net provides several ways for inter-process communication - including message queues, REST APIs, named/anonymous pipes, Memory-mapped files and a few more I haven't mentioned here.

If it's a one-way communication on a single computer (one process only writes, the other only reads), the simplest way would probably be using anonymous pipes. If it's a two-way communication, or it's over the network, you can use named pipes or memory-mapped files, or go with a more robust solution such as using a message queue.

答案2

得分: 0

我曾多次遇到过这样的问题。这是因为File类的Create、Delete、Write等方法性能下降。它没有合法的解决方案。但是,你可以使用以下的代码模式:(希望对你有帮助)

using System.Threading;

try {
    File.Delete(path);
} catch (Exception exc) {
    Threading.Sleep(500);

    try {
        File.Delete(path);
    } catch (Exception exc2) {
    }
}
英文:

I've faced such problems for many times. It is because Create, Delete, Write and other methods of File class undergo performance drop. It has no legitimate solution. But, you can use a code pattern like below: (I hope it will help you out)

import System.Threading;

try {
    File.Delete(path);
} catch (Exception exc) {
    Threading.Sleep(500);

    try {
        File.Delete(path);
    } catch (Exception exc2) {
    }
}

huangapple
  • 本文由 发表于 2023年8月10日 12:28:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76872652.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定