How to check if a file can be created inside given directory on MS XP/Vista?

只愿长相守 提交于 2019-11-30 21:25:09

I recently wrote a App to pass a set of test to obtain the ISV status from Microsoft and I also add that condition. The way I understood it was that if the user is Least Priveledge then he won't have permission to write in the system folders. So I approached the problem the the way Ishmaeel described. I try to create the file and catch the exception then inform the user that he doesn't have permission to write files to that directory.

In my understanding an Least-Priviledged user will not have the necessary permissions to write to those folders, if he has then he is not a Least-Priveledge user.

Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%?

In my opinion? Yes.

I wouldn't waste time and LOCs on checking for permissions. Ultimate test of file creation in Windows is the creation itself. Other factors may come into play (such as existing files (or worse, folders) with the same name, disk space, background processes. These conditions can even change between the time you make the initial check and the time you actually try to create your file.

So, if I had a scenario like that, I would just design my method to not lose any data in case of failure, to go ahead and try to create my file, and offer the user an option to change the selected directory and try again if creation fails.

dF.

I agree with the other answers that the way to do this is to try to create the file and catch the exception.

However, on Vista beware of UAC! See for example "Why does my application allow me to save files to the Windows and System32 folders in Vista?": To support old applications, Vista will "pretend" to create the file while in reality it creates it in the so-called Virtual Store under the current user's profile.

To avoid this you have to specifically tell Vista that you don't want administrative privileges, by including the appropriate commands in the .exe's manifest, see the question linked above.

import os
import tempfile

def can_create_file(folder_path):
    try:
        tempfile.TemporaryFile(dir=folder_path)
        return True
    except OSError:
        return False

def can_create_folder(folder_path):
    try:
        name = tempfile.mkdtemp(dir=folder_path)
        os.rmdir(name)
        return True
    except OSError:
        return False
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!