C#中,如何获得或设置文件属性(Attributes)
2008-04-29 16:18
489 查看
When testing for a single specific attribute, you need to use bitwise arithmetic. For example,consider the following faulty code:
if (myFile.Attributes == FileAttributes.ReadOnly)
...{ ... }
This test succeeds only if the read-only attribute is the only attribute for the current file. This israrely the case. If you want to successfully check whether the file is read-only, you need this codeinstead:
if ((myFile.Attributes & FileAttributes.ReadOnly) != 0)...{ ... }
When setting an attribute, you must also use bitwise arithmetic. In this case, you need to ensure
that you don’t inadvertently wipe out the other attributes that are already set.
// This sets the read-only attribute (and keeps all others as is).
myFile.Attributes = myFile.Attributes | FileAttributes.ReadOnly;
// This removes the read-only attribute (and keeps all others as is).
myFile.Attributes = myFile.Attributes & ~FileAttributes.ReadOnly;
if (myFile.Attributes == FileAttributes.ReadOnly)
...{ ... }
This test succeeds only if the read-only attribute is the only attribute for the current file. This israrely the case. If you want to successfully check whether the file is read-only, you need this codeinstead:
if ((myFile.Attributes & FileAttributes.ReadOnly) != 0)...{ ... }
When setting an attribute, you must also use bitwise arithmetic. In this case, you need to ensure
that you don’t inadvertently wipe out the other attributes that are already set.
// This sets the read-only attribute (and keeps all others as is).
myFile.Attributes = myFile.Attributes | FileAttributes.ReadOnly;
// This removes the read-only attribute (and keeps all others as is).
myFile.Attributes = myFile.Attributes & ~FileAttributes.ReadOnly;
相关文章推荐
- C#如何获得文件的版本号
- C#获取设置文件属性
- C# 如何重命名(无视是否只读、等文件侠属性)文件侠,与操作
- c# 设置属性的样式(选择文件)
- C#获得文件属性信息的实现方法
- 在VC中,如何修改文件的只读属性设置(转)
- Delphi dbf文件如何定位记录(即设置Table的RecNum属性来移动到该记录号)
- C# 如何运行时获得一个类的属性个数及其名字、类型
- 文件的生成操作,属性如何设置(内容/嵌入资源等)
- 如何设置才能获得电脑蓝屏产生的转储文件啊
- SQLite 引用属性 文件属性如何设置!?
- c#设置文件及文件夹的属性
- HTML控件ID和NAME属性的区别,以及如何在asp.net页面的.CS文件中获得.ASPX页面中HTML控件的值
- 如何使用DOS命令attrib设置文件或文件夹的属性
- 黄聪:[C#]VS中如何设置相关的partial 类文件嵌套在一个文件下
- HTML控件ID和NAME属性的区别,以及如何在asp.net页面的.CS文件中获得.ASPX页面中HTML控件的值
- HTML控件ID和NAME属性的区别,以及如何在asp.net页面的.CS文件中获得.ASPX页面中HTML控件的值(转载)
- 获得Windows系统中文件属性——GetFileAttributes详解
- 如何用C#获得文件信息以及扩展信息
- C#复制文件、设置隐藏,只读属性