设置“隐藏” Windows OS中的文件夹上的属性? [英] Set "hide" attribute on folders in windows OS?

查看:101
本文介绍了设置“隐藏” Windows OS中的文件夹上的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图隐藏文件夹失败。我发现了这个:

Trying to hide folder without success. I've found this :

import ctypes
ctypes.windll.kernel32.SetFileAttributesW('G:\Dir\folder1', 2)

但它对我不起作用。我在做什么错?

but it did not work for me. What am I doing wrong?

推荐答案

您的代码有两件事,都与文件夹名称文字有关。 SetFileAttributesW()函数需要Unicode字符串参数。您可以通过在字符串前面加上字符 u 来指定其中之一。其次,字符串中的任何文字反斜杠字符都必须加倍,或者您也可以在其中添加 r 前缀。紧接在下面的代码中使用一个双前缀。

There are two things wrong with your code, both having to do with the folder name literal. The SetFileAttributesW() function requires a Unicode string argument. You can specify one of those by prefixing a string with the character u. Secondly, any literal backslash characters in the string will have to be doubled or you could [also] add an r prefix to it. A dual prefix is used in the code immediately below.

import ctypes
FILE_ATTRIBUTE_HIDDEN = 0x02

ret = ctypes.windll.kernel32.SetFileAttributesW(ur'G:\Dir\folder1',
                                                FILE_ATTRIBUTE_HIDDEN)
if ret:
    print('attribute set to Hidden')
else:  # return code of zero indicates failure -- raise a Windows error
    raise ctypes.WinError()

您可以找到Windows的系统错误代码此处。要在资源管理器中查看属性更改的结果,请确保未启用其显示隐藏文件选项

You can find Windows' system error codes here. To see the results of the attribute change in Explorer, make sure its "Show hidden files" option isn't enabled.

@eryksun在关于安排自动将字节字符串转换为Unicode的评论中说,您需要在调用该函数以指定其参数的正确转换之前执行以下 。 @eryksun还解释了为什么在WinAPI函数的 W 版本中,这不是指向字符串的默认指针的原因-请参见注释。
https://docs.microsoft。 com / en-us / windows / win32 / debug / system-error-codes
ctypes.windll.kernel32.SetFileAttributesW.argtypes =(
ctypes.c_wchar_p,ctypes.c_uint32)

To illustrate what @eryksun said in a comment about arranging for the conversion to Unicode from byte strings to happen automatically, you would need to do the following before calling the function to specify the proper conversion of its arguments. @eryksun also has an explanation for why this isn't the default for pointers-to-strings in the W versions of the WinAPI functions -- see the comments. https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes ctypes.windll.kernel32.SetFileAttributesW.argtypes = ( ctypes.c_wchar_p, ctypes.c_uint32)

然后,这将起作用(请注意,由于反斜杠,仍需要 r 前缀):

Then afterwards, this will work (note that an r prefix is still required due to the backslashes):

ret = ctypes.windll.kernel32.SetFileAttributesW(r'G:\Dir\folder1',
                                                FILE_ATTRIBUTE_HIDDEN)

这篇关于设置“隐藏” Windows OS中的文件夹上的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆