H o m e

 

A t t r i b u t e s   P r o p e r t y   O f   T h e   F i l e I n f o   C l a s s

By Michael McIntyre

mikemc@getdotnetcode.com

 

The Attributes property of the System.IO.FileInfo class is used to get or set file attributes.  Some commonly used file attributes are Archive, Compressed, Directory, Encrypted, Hidden, Normal, ReadOnly, System, and Temporary.

 

Bitwise arithmetic with the And and Or keywords is used to examine or modify a file’s attributes. Because a file can have any combination of attributes, the Attributes property accepts a combination of enumerated values.

 

Example: Get and Set a file’s ReadOnly Attribute

 

1.  Add a text file named DemoAttributes.txt to your C directory.

 

2.  Start a new Visual Studio.Net VB.NET Windows Forms project. 

 

3.  To Form1 add an Imports statement:

 

Imports System.IO

 

4.  Add a Button to Form1.  Name it GetReadOnlyAttributeButton. Add the code below to its Click handler.

 

' Declare and instantiate a FileInfo object.

Dim aFileInfo As New System.IO.FileInfo("C:\DemoAttributes.txt")

' Use Bitwise arithmetic to check a file's ReadOnly attribute.

If (aFileInfo.Attributes And FileAttributes.ReadOnly) = FileAttributes.ReadOnly Then

    MessageBox.Show(aFileInfo.Name & " is ReadOnly")

 Else

    MessageBox.Show(aFileInfo.Name & " is NOT ReadOnly")

End If

 

5. Add a Button to Form1. Name it SetReadOnlyButton.  Add the code below to its Click handler.

 

' Declare and instantiate a FileInfo object.

Dim aFileInfo As New System.IO.FileInfo("C:\DemoAttributes.txt")

' Use Bitwise arithmetic to change the file's ReadOnly attribute.

aFileInfo.Attributes = aFileInfo.Attributes Or FileAttributes.ReadOnly

 

6. Add a Button to Form1. Name it SetNotReadOnlyButton. Add the code below to its Click handler.

 

' Declare and instantiate a FileInfo object.

Dim aFileInfo As New System.IO.FileInfo("C:\DemoAttributes.txt")

' Use Bitwise arithmetic to change the file's ReadOnly attribute.

aFileInfo.Attributes = aFileInfo.Attributes And Not FileAttributes.ReadOnly

 

7. Run the application.

 

8.  Click the GetReadOnlyAttributeButton. 

 

Result: DemoAttributes.txt is NOT ReadOnly

 

9.  Click the SetReadOnlyButton, then the GetReadOnlyAttributeButton. 

 

Result: DemoAttributes.txt is ReadOnly

 

10. Click the SetNotReadOnlyButton, then the GetReadOnlyAttributeButton.

 

Result: DemoAttributes.txt is NOT ReadOnly

 

This example has provided some code patterns that show how to use a FileInfo object and bitwise arithmetic to GET or SET file attributes.

 

To learn more about Bitwise arithmetic visit: Arithmetic Operators (look for the Bitwase Operations section)

 

To learn more about using a FileInfo object visit:  FileInfo Class

 

Copyright © 2001-2003 aZ Software Developers. All rights reserved.