如何检查目录是否只读 [英] How to check whether a directory is readonly

查看:91
本文介绍了如何检查目录是否只读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我需要检查一个目录是否只读。如果只读是真的那么我需要删除它。我怎么能用C#做这件事。



framework2.0



谢谢

nidheesh

hi all,

i need to check whether a directory is read only. if read only is true then i need to remove that. how can i do this using C#.

framework2.0

thanks
nidheesh

推荐答案

看一下这个问题 [ ^ ]。


OP说他已经尝试过以下代码来测试是否目录是只读的:



OP says he has tried the following code to test whether a directory is read-only:

DirectoryInfo di = new DirectoryInfo(@"e:\\test");
if (di.Attributes == FileAttributes.ReadOnly)
{
    MessageBox.Show("Read only"); }
else
{
    MessageBox.Show("No");
}





这是几乎正确,它只是没有考虑到这个事实Attributes属性是一个flag枚举,这意味着它可以设置为可用的组合 /system.io.fileattributes.aspx\"> FileAttributes [ ^ ]值。



换句话说,对于文件夹,Attributes属性至少包含 FileAttributes.Directory ,以及可能设置的任何其他标志(如 ReadOnly 标志)。



如果我们只对特定的标志感兴趣(在这种情况下,它是否是只读的),我们需要这样做:



This is almost correct, it just doesn't take into account the fact that the Attributes property is a "flag" enum, meaning that it can be set to any combination of the available FileAttributes[^] values.

In other words, for a folder, the Attributes property will contain at least FileAttributes.Directory, along with any other flags that may be set (like the ReadOnly flag).

If we're only interested in a particular flag (in this case, whether it's read-only), we need to do this:

if ((di.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)





t的其余部分代码可以保持原样。



要清除文件夹中的只读标志,需要在Attributes属性中取消设置ReadOnly标志:





The rest of the code can stay as-is.

To clear the read-only flag from a folder, you need to unset the ReadOnly flag in the Attributes property:

di.Attributes = (di.Attributes ^ FileAttributes.ReadOnly); // This clears just the ReadOnly flag, the rest of the flags stay the same.



请注意,如果您没有正确的权限进行更改,这可能会失败到这个文件夹,或者它是一个系统文件夹(即它设置了 FileAttributes.System 标志)。



希望这会有所帮助。


Note that this may fail if you don't have the correct permissions to make changes to this folder, or if it's a system folder (i.e. it has the FileAttributes.System flag set).

Hope this helps.


有一个函数HasAttribute

从未使用它但是这应该有效:

There is a function HasAttribute
Never used it though but this shall work:
DirectoryInfo di = new DirectoryInfo(@"e:\\test");
if (di.Attributes.HasFlag(FileAttributes.ReadOnly))
{
    //Your Logic Here
}


这篇关于如何检查目录是否只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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