9.2 Set File and Directory Attributes


Problem

You need to test or modify file or directory attributes.

Solution

Create a System.IO.FileInfo object for a file or a System.IO.DirectoryInfo object for a directory and use the bitwise AND (&) and OR ( ) arithmetic operators to modify the value of the Attributes property.

Discussion

The FileInfo.Attributes and DirectoryInfo.Attributes properties represent file attributes such as archive, system, hidden, read-only, compressed, and encrypted. (Refer to the MSDN reference for the full list.) Because a file can possess any combination of attributes, the Attributes property accepts a combination of enumerated values. To individually test for a single attribute or change a single attribute, you need to use bitwise arithmetic.

For example, consider the following code, which takes a read-only test file and checks for the read-only attribute.

 using System; using System.IO; public class Attributes {     private static void Main() {         // This file has the archive and read-only attributes.         FileInfo file = new FileInfo("data.txt");         // This displays the string "ReadOnly, Archive "         Console.WriteLine(file.Attributes.ToString());         // This test fails, because other attributes are set.         if (file.Attributes == FileAttributes.ReadOnly) {             Console.WriteLine("File is read-only (faulty test).");         }         // This test succeeds, because it filters out just the         // read-only attribute.         if ((file.Attributes & FileAttributes.ReadOnly) ==           FileAttributes.ReadOnly) {             Console.WriteLine("File is read-only (correct test).");         }         Console.ReadLine();     } } 
Note  

To understand how the preceding code works, you need to realize that the Attributes setting is made up (in binary) of a series of ones and zeros, such as 00010011. Each 1 represents an attribute that is present, while each represents an attribute that is not. When you use a bitwise AND (&) operation, it compares each individual digit against each digit in the enumerated value. For example, if you bitwise AND a value of 00100001 (representing an individual file's archive and read-only attributes) with the enumerated value 00000001 (which represents the read-only flag), the resulting value will be 00000001 ”it will have a 1 only where it can be matched in both values.

When setting an attribute, you must also use bitwise arithmetic. In this case, it's needed to ensure that you don't inadvertently wipe out the other attributes.

 // This adds just the read-only attribute. file.Attributes = file.Attributes  FileAttributes.ReadOnly; // This removes just the read-only attribute. file.Attributes = file.Attributes & ~FileAttributes.ReadOnly; 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net