How to test if directory is hidden in C#?
Asked Answered
C

4

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?

Camiecamila answered 17/8, 2009 at 16:22 Comment(0)
H
39

In .NET 4.0 you can do:

dir.Attributes.HasFlag(FileAttributes.Hidden)
Hardandfast answered 29/7, 2010 at 4:14 Comment(1)
The HasFlags() method is a new addition to .NET 4. It's much easier to use than the old bitwise comparison.Despond
N
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.

Notability answered 17/8, 2009 at 16:26 Comment(0)
L
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)
Lip answered 17/8, 2009 at 16:26 Comment(2)
Only problem is when I try evaluate the above, it still by passes... even though the directory is really hiddenCamiecamila
Sorry, thought you were looking for hidden directories, not excluding them. Fixed above code.Lip
E
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
Epiglottis answered 30/8, 2010 at 16:6 Comment(1)
This is highly inefficient, use dir.Attributes.HasFlag(FileAttributes.Hidden)Mesquite

© 2022 - 2024 — McMap. All rights reserved.