26

I have this loop:

  foreach (DirectoryInfo dir in downloadedMessageInfo.GetDirectories())
        {
            if (dir.Attributes != FileAttributes.Hidden)
            {
                dir.Delete(true);
            }
        }

How can I correctly skip all hidden directories?

JL.
  • 78,954
  • 126
  • 311
  • 459

4 Answers4

38

In .NET 4.0 you can do:

dir.Attributes.HasFlag(FileAttributes.Hidden)
Hallgrim
  • 15,143
  • 10
  • 46
  • 54
Alex
  • 396
  • 3
  • 2
  • The HasFlags() method is a new addition to .NET 4. It's much easier to use than the old bitwise comparison. – dthrasher Oct 12 '10 at 20:55
37

Change your if statement to:

if ((dir.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)

You need to use the bitmask since Attributes is a flag enum. It can have multiple values, so hidden folders may be hidden AND another flag. The above syntax will check for this correctly.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
16

Attributes is a Flags value, so you need to check if it contains FileAttributes.Hidden using a bitwise comparison, like this:

if ((dir.Attributes & FileAttributes.Hidden) == 0)
bdukes
  • 152,002
  • 23
  • 148
  • 175
  • Only problem is when I try evaluate the above, it still by passes... even though the directory is really hidden – JL. Aug 17 '09 at 16:29
  • 1
    Sorry, thought you were looking _for_ hidden directories, not excluding them. Fixed above code. – bdukes Aug 17 '09 at 17:07
1

This code works for me in VB.Net;

If (dir.Attributes.Tostring.Contains("Hidden") Then
    ' File is hidden
Else
    ' File is not hidden
EndIf
user435136
  • 19
  • 1