Changing folder visibility status

howester77

Active member
Joined
Aug 5, 2005
Messages
38
Programming Experience
5-10
How do you change a folder from being "normal" to "hidden" using vb.net?
 
The Attributes property of the FileInfo class is a bitwise combination of FileAttributes values. That means that each bit in the value represents an attribute and that attribute is set if the bit is 1 and not set if the bit is zero. You turn individual attributes on and off using bitwise operations:
VB.NET:
Dim fi As New IO.FileInfo("file path here")

'Set the Hidden attribute.
fi.Attributes = fi.Attributes Or IO.FileAttributes.Hidden

'Remove the Hidden attribute.
fi.Attributes = fi.Attributes And Not IO.FileAttributes.Hidden

'Toggle the Hidden attribute.
fi.Attributes = fi.Attributes Xor IO.FileAttributes.Hidden
Here's a simplified explanation of how that works. I'll use 8-bit values instead of 32-bit for simplicity. The FileAttributes.Hidden value is 2, so in binary this looks like 00000010. Let's say that in binary the current value of the Attributes property is abcdefgh, where each character represents a 1 or a zero. When you do a bitwise Or, each bit in the result will be set if the corresponding bit in either of the operands is set, so if you Or the two values together you get:

abcdefgh Or 00000010 = abcdef1h

so the Hidden bit is set in the result regardless of whether it was set in the original Attributes property or no.

A bitwise Not will switch the value of every bit, so if you Not the Hidden value you get:

Not 00000010 = 11111101

A bitwise And will set a bit in the result if the corresponding bit is set in both the operands, so if you And the two values you get:

abcdefgh And 11111101 = abcdef0h

so the Hidden bit is not set regardless of whether it was in the original property value.

A bitwise Xor (exclusive or) will set a bit in the result if the corresponding bit was set in one and only one of the operands, so you can toggle the Hidden attribute with a Xor like so:

abcdef1h Xor 00000010 = abcdef0h (bit set in both operands so not set in result)
abcdef0h Xor 00000010 = abcdef1h (bit set in one operand so is set in result)
 
Oops. Fixed an error in the code where the "Not" was missing from the line that removes the attribute. Also note that this type of operation can be performed on any enumerated type that is declared with the Flags attribute.
 
Back
Top