New to C# and I don't really understand how the below code is determining if the file is read-only or not. In particular, how does the (attributes & FileAttributes.ReadOnly) evaluate to something that does or doesn't == FileAttributes.ReadOnly.
I'm guessing the & is doing some sort of bitwise AND?? I just don't follow how this works. Can anyone provide an explanation?
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");
}
}
}
}
The statement attributes & FileAttributes.ReadOnly is a bitwise AND. This means that it will return the value of FileAttributes.ReadOnly if the appropriate bit is set in attributes, otherwise it will return 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.
The reason for this, is because a file can have many attributes set. For example, it can be a Hidden (value 2), ReadOnly (value 1), System (value 4) file. The attributes for that file would be the bitwise OR of all of those attributes. The value of the file's attribute would be 1+2+4 = 7.
Performing a simple equality check, e.g.
if ( attributes == FileAttributes.ReadOnly )
would return false, because the 7 != 1. But the bitwise AND, does show the read only bit is set. In binary this looks like:
Attributes: 0111
ReadOnly : 0001
AND : 0001
As has been pointed out by @cadrell0, the enum type can take care of this for you using the HasFlag method. The check for the readonly flag becomes much simpler, and looks like
if ( attributes.HasFlag( FileAttributes.ReadOnly ) )
{
Console.WriteLine("read-only file");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With