趣文网 > 作文大全

C 去除文件和文件夹的只读属性

2020-12-02 18:40:01
相关推荐

在使用 DirectoryInfo dir = Directory.CreateDirectory(pathName) 创建目录或者创建一个文件后,有时候作为临时文件用完以后需要删除掉,使用File.delete()或者Directory.Delete()经常会遇到“访问被拒绝的错误”;

这时我们需要设置文件或者文件夹的只读属性,再进行删除。

去除文件夹的只读属性: System.IO.DirectoryInfo DirInfo = new DirectoryInfo(“filepath”);

DirInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;

去除文件的只读属性:System.IO.File.SetAttributes("filepath", System.IO.FileAttributes.Normal);

FileAttributes 枚举

提供文件和目录的属性。

此枚举有一个 FlagsAttribute 属性,允许其成员值按位组合。

命名空间:System.IO

程序集:mscorlib(在 mscorlib.dll 中)

语法

[SerializableAttribute]

[FlagsAttribute]

[ComVisibleAttribute(true)]

public enum FileAttributes

FileAttributes的简单应用

常用的FileAttributes成员有Hidden,System,Archive,ReadOnly,Directory等等。这些对象可以进行位域运算,通过位或运算给文件附上属性。如:File.setAttribute(filename,FileAttribute.Hidden|FileAttribute.ReadOnly)则,filename文件就拥有Hidden和ReadOnly两种属性。

在数值和标志枚举常量之间执行按位“与”操作就可以测试数值中是否已设置标志,这种方法会将数值中与标志不对应的所有位都设置为零,然后测试该操作的结果是否等于该标志枚举常量。

仍然是MSDN中的例子:

using System;

using System.IO;

using System.Text;

class Test

{

public static void Main()

{

string path = @"c:tempMyTest.txt";

// Create the file if it does not exist.

if (!File.Exists(path))

{

File.Create(path);

}

if ((File.GetAttributes(path) & FileAttributes.Hidden) == FileAttributes.Hidden)

{

// Show the file.

File.SetAttributes(path, FileAttributes.Archive);

Console.WriteLine("The {0} file is no longer hidden.", path);

}

else

{

// Hide the file.

File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);

Console.WriteLine("The {0} file is now hidden.", path);

}

}

}

ps:FileAttributes.Archive是文档的存档状态,应用程序使用该属性为文件加上备份或删除标记。

阅读剩余内容
网友评论
显示评论内容(2) 收起评论内容
  1. 2021-08-08 03:31迎着阳光,勾出一丝浅笑。[北京市网友]IP:920647798
    终于不用再一个一个文件夹地去修改只读属性了,省时省力!赞一个!
    顶7踩0
  2. 2020-03-15 17:32Amber[吉林省网友]IP:3389978143
    这个功能太方便了,之前总是遇到无法删除或修改只读文件的问题,现在终于解决了。
    顶9踩0
相关内容
延伸阅读
小编推荐

大家都在看

关于父爱的作文 游记作文500字 尊重作文 英语作文我的朋友 我的同学作文 生活作文 写事的作文200字 我的心愿作文600字 高考高分作文 追星作文 自我介绍作文 400字的作文 优秀作文400字可抄免费 描写桃花的作文 小学英语作文 四年级下册语文第一单元作文 描写秋天的作文 愿望作文 英语作文题目 小猫的作文 我的心爱之物作文500字 科技改变生活作文 多彩的活动作文 他笑了作文 春雨作文 向日葵作文 追梦作文 六年级上册语文作文 秋天的作文300字 做最好的自己作文