Use Bitwise Arithmetic with File Attributes

Problem

You want to correct examine or modify file attribute information.

Solution

Use bitwise arithmetic with the And and Or keywords.

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:

' This file has the archive, read-only, and encrypted attributes. Dim MyFile As ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.