tags:

views:

1044

answers:

4

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?

+7  A: 

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
Only problem is when I try evaluate the above, it still by passes... even though the directory is really hidden
JL
Sorry, thought you were looking _for_ hidden directories, not excluding them. Fixed above code.
bdukes
+13  A: 

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
+1  A: 
dir.Attributes.HasFlag(FileAttributes.Hidden)
Alex
The HasFlags() method is a new addition to .NET 4. It's much easier to use than the old bitwise comparison.
dthrasher
A: 

This code works for me in VB.Net;

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