簡體   English   中英

進程關閉后刪除文件。 C#Windows表單

[英]Delete a file after process is close. C# windows forms

我有一個Windows Forms應用程序,該應用程序在運行時使用臨時文件,並在關閉主窗體后將其刪除。 關鍵是,如果我通過殺死進程從任務管理器中關閉程序,該文件不會被刪除。

當以某種方式(而不是表單)關閉該進程時,是否可以自動刪除文件?

您可以按照此用例的FileOptions枚舉文檔中的描述使用FileOptions.DeleteOnClose

文檔狀態為DeleteOnClose

指示不再使用文件時將其自動刪除。

另一個解決方案(非常容易理解)是,如果您的進程存在,則使用陷阱陷阱,我在很多程序中都使用此解決方案進行監督(我不是該想法的作者,不記得我在哪里找到了這個想法,我剛剛修改了代碼):您可以在退出的事件中刪除臨時文件。

    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.");
        }
    }

必須有更好的方法來檢查是否被殺死,或者是在任務管理器中捕獲一條消息,或者掛接到任務管理器。 但是,解決方案變得更加復雜

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM