开发者

Is it possible to create a process which will always clean up after itself?

I'd like to create a new process which will clean up after itself, even if the calling process has terminated. I've mocked up an example be开发者_StackOverflowlow, using notepad to display a temporary file, which I'd like to be deleted after notepad is closed.

In the code below, this works as expected if I uncomment the WaitForExit() line or alternatively go into a infinite loop to mimic the calling program running. The main problem is when the calling program finishes, since the event is no longer handled.

I'd appreciate any suggestions on how to handle this case.

Regards,

Chris

    static void Main(string[] args)
    {
        string filename = @"c:\temp\example.txt";
        if (!File.Exists(filename))
            File.WriteAllText(filename, "abc");

        ProcessStartInfo psi = new ProcessStartInfo("notepad", filename);

        Process cmdProcess = new Process();

        Process p = new Process();
        psi.CreateNoWindow = true;
        p.EnableRaisingEvents = true;
        p.StartInfo = psi;
        p.Exited += (sender, e) => { File.Delete(filename); };

        p.Start();
        //p.WaitForExit();
    }


A sneaky way would to write a batch file which does approx this:

notepad c:\temp\example.txt
del c:\temp\example.txt

and then have your process execute the batch instead.

Working sample (save as c:\test.bat):

echo FOO > c:\test.txt
notepad c:\test.txt
del c:\test.txt
del c:\test.bat


If the calling process has exited it can no longer do anything; it doesn't exist.

One option would be to create another thread that is not a background thread (set IsBackground to false) and call WaitForExit on that thread; that will keep the process alive during normal exit from Main. However, this cannot do anything if the process terminates abnormally (task manager kill, or simply pulling out the power).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜