How do I automatically delete tempfiles in c#?

后端 未结 9 1673
旧巷少年郎
旧巷少年郎 2020-12-04 11:35

What are a good way to ensure that a tempfile is deleted if my application closes or crashes? Ideally I would like to obtain a tempfile, use it and then forget about it.

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 11:56

    I'm not primarily a C# programmer, but in C++ I'd use RAII for this. There are some hints on using RAII-like behaviour in C# online, but most seem to use the finalizer — which is not deterministic.

    I think there are some Windows SDK functions to create temporary files, but don't know if they are automatically deleted on program termination. There is the GetTempPath function, but files there are only deleted when you log out or restart, IIRC.

    P.S. The C# destructor documentation says you can and should release resources there, which I find a bit odd. If so, you could simply delete the tempfile in the destructor, but again, this might not be completely deterministic.

提交回复
热议问题