2013-05-29 126 views
1

C#的新手和我真的不知道下面的代码是如何确定文件是否是只读的。特别是,(属性&FileAttributes.ReadOnly)如何评估某些不存在或不存在== FileAttributes.ReadOnly。检查FileAttributes枚举

我猜&正在做某种按位AND?我只是不遵循这个如何工作。任何人都可以提供解释吗?

using System; 
using System.IO; 

namespace ConsoleApplication 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      FileAttributes attributes = File.GetAttributes("c:/Temp/testfile.txt"); 
      if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) 
      { 
       Console.WriteLine("read-only file"); 
      } 
      else 
      { 
       Console.WriteLine("not read-only file"); 
      } 
     } 
    } 
} 

回答

3

声明attributes & FileAttributes.ReadOnlybitwise AND。这意味着,它会返回的FileAttributes.ReadOnly的值,如果相应位中设定attributes,否则将返回0。

的逐位AND需要两个相等长度的二进制表示,并对每一对逻辑与运算的相应位。如果第一位是1并且第二位是1,则每个位置的结果是1;否则,结果为0.

原因是因为一个文件可能有很多attributes集。例如,它可以是Hidden(值2),ReadOnly(值1),System(值4)文件。该文件的属性将是所有这些属性的按位或。文件属性值为1 + 2 + 4 = 7。

执行简单的相等性检查,例如,

if (attributes == FileAttributes.ReadOnly) 

会返回false,因为7 != 1。但是按位与,显示只读位被设置。在二进制这个样子:

Attributes: 0111 
ReadOnly : 0001 
AND  : 0001 

如已通过@ cadrell0指出的那样,enum类型,使用方法HasFlag可以照顾这对你。对于只读标志的检查就变得简单多了,貌似

if (attributes.HasFlag(FileAttributes.ReadOnly)) 
{ 
    Console.WriteLine("read-only file"); 
+0

不要忘了[HasFlag(http://msdn.microsoft.com/en-us/library/system.enum.hasflag。 aspx)方法。我确定它在内部也做同样的事情,但我认为它比按位操作更清晰。 – cadrell0

+0

@ cadrell0感谢提醒,回复更新:) – Steve