gpt4 book ai didi

c# - 检查 FileAttributes 枚举

转载 作者:行者123 更新时间:2023-11-30 20:57:26 25 4
gpt4 key购买 nike

C# 的新手,我不太明白下面的代码是如何确定文件是否只读的。特别是,(attributes & FileAttributes.ReadOnly) 如何计算为做或不做的事情 == FileAttributes.ReadOnly。

我猜 & 正在做某种按位与??我只是不了解这是如何工作的。谁能解释一下?

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.ReadOnlybitwise AND .这意味着如果在 attributes 中设置了适当的位,它将返回 FileAttributes.ReadOnly 的值,否则将返回 0。

A bitwise AND takes two binary representations of equal length and performs the logical AND operation on each pair of corresponding bits. The result in each position is 1 if the first bit is 1 and the second bit is 1; otherwise, the result is 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");

关于c# - 检查 FileAttributes 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16822760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com