The correct way to check the directory is writable

I recently added GetTempPath to the application. During the code review, it was emphasized that the GetTempPath description contains information:

The application should check for the path and the appropriate path permissions before any use for file I / O.

Now all access to the files is wrapped in try / catch blocks, and what system will be there that does not have access to its own temporary directory?

My initial idea would be to attempt to create directories if they do not exist (via GetFileAttributes and CreateDirectory), and then to create the file, write the byte, and then delete the file. Although this will work, it smells of ignorance - is there probably the best way to verify that you have write access to a folder?

I began to search and find file attribute constants, common permissions, standard permissions, file permissions constants and the GetSecurityInfo function. All this seemed to create a solution that was longer than creating the file and see if it adheres to the method.

So, what is the correct way to use WinAPI authentication features, do you have write access to the folder?

+4
source share
2 answers

MSDN is misleading. You might want to check if a path exists (and if not, create one), but the only way to find out if you can write there, write there.

Also, just because you can write there does not mean that you can write there later. The user or other programs can delete things, change security settings, block directories, etc. Trying to pre-verify that a place you can write is a waste of time. Just write when you need to and be prepared for a crash.

+4
source

It is best to try to write files to a directory. If the record failed due to lack of rights, then the error code will tell you about it. Find ERROR_ACCESS_DENIED .

If you try to do this in any other way, you will simply copy the system code, which still had to run. And you have little chance of reproducing it for current versions of Windows and future versions.

There is no need to create a file and write one byte to it. Suppose you have write access to a temporary folder and you are trying to write the entire file (s) that you need. If you ever experience failure, you can also complete the process. There is not much point if you cannot write to a temporary folder.

+3
source

Source: https://habr.com/ru/post/1392487/


All Articles