Set File and Directory Attributes

To test or modify file or directory attributes.

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();
    }
}

// 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;

Technorati :

No comments:

Post a Comment