C# 检查FileAttributes枚举
我是C#新手,我不太明白下面的代码是如何确定文件是否为只读的。特别是,(attributes&FileAttributes.ReadOnly)如何计算为执行或不执行==FileAttributes.ReadOnly 我猜-,正在做一些按位和??我只是不明白这是怎么回事。有人能解释一下吗C# 检查FileAttributes枚举,c#,C#,我是C#新手,我不太明白下面的代码是如何确定文件是否为只读的。特别是,(attributes&FileAttributes.ReadOnly)如何计算为执行或不执行==FileAttributes.ReadOnly 我猜-,正在做一些按位和??我只是不明白这是怎么回事。有人能解释一下吗 using System; using System.IO; namespace ConsoleApplication { class Program { static void
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");
}
}
}
}
语句
attributes&FileAttributes.ReadOnly
是一个。这意味着它将返回FileAttributes.ReadOnly的值,如果在attributes
中设置了适当的位,则它将返回0
按位AND采用两种长度相等的二进制表示,并对每对对应位执行逻辑AND运算。如果第一位为1,第二位为1,则每个位置的结果为1;否则,结果为0
这样做的原因是,一个文件可以有多个集合。例如,它可以是隐藏的
(值2)、只读的
(值1)、系统
(值4)文件。该文件的属性将是所有这些属性的按位OR。文件属性的值为1+2+4=7
执行简单的相等性检查,例如
if ( attributes == FileAttributes.ReadOnly )
将返回false,因为7!=1
。但按位AND显示设置了只读位。在二进制中,这看起来像:
Attributes: 0111
ReadOnly : 0001
AND : 0001
正如@cadrell0所指出的,enum
类型可以使用该方法为您解决这个问题。readonly标志的检查变得简单多了,如下所示
if ( attributes.HasFlag( FileAttributes.ReadOnly ) )
{
Console.WriteLine("read-only file");
语句attributes&FileAttributes.ReadOnly
是一个。这意味着它将返回FileAttributes.ReadOnly的值,如果在attributes
中设置了适当的位,则它将返回0
按位AND采用两种长度相等的二进制表示,并对每对对应位执行逻辑AND运算。如果第一位为1,第二位为1,则每个位置的结果为1;否则,结果为0
这样做的原因是,一个文件可以有多个集合。例如,它可以是隐藏的
(值2)、只读的
(值1)、系统
(值4)文件。该文件的属性将是所有这些属性的按位OR。文件属性的值为1+2+4=7
执行简单的相等性检查,例如
if ( attributes == FileAttributes.ReadOnly )
将返回false,因为7!=1
。但按位AND显示设置了只读位。在二进制中,这看起来像:
Attributes: 0111
ReadOnly : 0001
AND : 0001
正如@cadrell0所指出的,enum
类型可以使用该方法为您解决这个问题。readonly标志的检查变得简单多了,如下所示
if ( attributes.HasFlag( FileAttributes.ReadOnly ) )
{
Console.WriteLine("read-only file");
别忘了方法。我确信它在内部做同样的事情,但我认为它比按位操作更清晰。不要忘记这个方法。我确信它在内部做同样的事情,但我认为它比按位操作更清晰。