开发者

Getting safe temp folder in Windows

I need to get a safe temp folder where I could store temporary files for my application, but so far my research has lead me to conclusion that all approaches I've found are flawed.

The first idea was to use GetTempPath function, but that causes two problems:

  • The folder might not exist, so I would have to truncate folders one by one up to root, and recreate them if they do not exist back to full path (error prone, tedious)
  • From "Larry Osterman's WebLog" click it seems that GetTempPath might fallback to USERPROFILE or Windows directory and extract whole lot of files right in there, which is SUPER BAD(TM)!

In the same post, there is a suggestion to use GetEnvironmentVariable, but this seems 开发者_JAVA技巧a dangerous function to me (missing TMP & TEMP envvars for instance).

Is there a cleaner function I could use? Seems that SHGetKnownFolderPath has no clue what temp folder is.


Your program is probably not the only one to rely on GetTempPath, so it's reasonable to expect it to return a proper writable path. Especially since Windows automatically initializes the TMP and TEMP environment variables for you; someone would have to go to some trouble to override them, and it would be their responsibility to make sure the change did not mess up their system.

I would go ahead and assume GetTempPath works properly, and worry about failures when you try to create the temporary file - there are other errors that might occur at that time that you need to check for anyway.


An idea would be to get the path where your application is (GetModuleFileNameEx combined with GetModuleHandle(NULL) and GetCurrentProcess) since this directory cannot be deleted under windows as long as your application is running from it (maybe I'm wrong ...some years ago I couldn't do this :) ) and in this directory create a temporary directory.


Your first bullet point is the solution. Wrap it up in a method so that you don't duplicate code.


According to this answer, Boost's Filesystem library can be used for this.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜