进程关闭后删除文件。C# 窗体

我有一个 Windows 窗体应用程序,它在应用程序运行时使用临时文件,并在主窗体关闭后将其删除。问题是,如果我通过终止进程从任务管理器中关闭程序,则文件不会被删除。

当进程以任何方式而不是表单关闭时,有没有办法自动删除文件?


波斯汪
浏览 371回答 2
2回答

缥缈止盈

您可以按照此用例的FileOptions EnumFileOptions.DeleteOnClose文档中的说明使用。DeleteOnClose的文档说明:表示文件不再使用时会自动删除。

holdtom

另一个解决方案(很容易理解)是使用一个帮助程序,如果你的进程存在,我在我的很多程序中使用这个解决方案来监督(我不是这个想法的作者,不记得我在哪里找到这个想法,我刚刚修改了代码):您可以删除退出事件中的临时文件..    static void Main(string[] args)    {        //Main App Process.        if (args.Length == 0)        {            //Saves current process info to pass on command line.            main = Process.GetCurrentProcess();            mainProcessID = main.Id;            //Initializes the helper process            checker = new Process();            checker.StartInfo.FileName = main.MainModule.FileName;            checker.StartInfo.Arguments = mainProcessID.ToString();            checker.EnableRaisingEvents = true;            checker.Exited += new EventHandler(checker_Exited);            //Launch the helper process.            checker.Start();            Application.Run(new MainForm()); // your winform app        }        else //On the helper Process        {            main = Process.GetProcessById(int.Parse(args[0]));            main.EnableRaisingEvents = true;            main.Exited += new EventHandler(main_Exited);            while (!main.HasExited)            {                Thread.Sleep(1000); //Wait 1 second.             }            //Provide some time to process the main_Exited event.             Thread.Sleep(2000);        }    }    //Double checks the user not closing the checker process.    static void checker_Exited(object sender, EventArgs e)    {                   //This only checks for the task manager process running.         //It does not make sure that the app has been closed by it. But close enough.        //If you can think of a better way please let me know.        if (Process.GetProcessesByName("taskmgr").Length != 0)        {            MessageBox.Show("Task Manager killed helper process.");            //If you like you could kill the main app here to.             //main.Kill();        }    }    //Only gets to run on the checker process. The other one should be dead.     static void main_Exited(object sender, EventArgs e)    {        //This only checks for the task manager process running.         //It does not make sure that the app has been closed by it. But close enough.        //If you can think of a better way please let me know.        if (Process.GetProcessesByName("taskmgr").Length != 0)        {            MessageBox.Show("Task Manager killed my application.");        }    }必须有更好的方法来检查杀戮,可能是在任务管理器上捕获消息,或者挂钩到任务管理器。但是,解决方案变得更加复杂
打开App,查看更多内容
随时随地看视频慕课网APP