views:

134

answers:

6

Is there an easier way to test if a file system item is a directory than using bitmasks?

I have this code in one of my applications (two second line is actually in a loop over folderItems but for simplicity assume the first element):

Dim folderItems As String() = Directory.GetFileSystemEntries(aFolder)
Dim someDirItem As String = folderItems(0)
Dim fInfo As System.IO.FileInfo = New System.IO.FileInfo(someDirItem)
Dim isDirectory As Boolean = (CInt(fInfo.Attributes) And CInt(FileAttributes.Directory)) > 0

(FileAttributes.Directory is 16).

This works, but is there an easier way than using bitwise AND with 1000 (base 2)?

A: 

Bitwise comparisons are difficult? If you really don't like doing it this way just write a utility class that exposes a data structure of booleans and just port it around in your projects.

Spencer Ruport
+11  A: 

How about:

System.IO.Directory.Exists(fullPath)

Returns true if fullPath is a directory.

Jay Riggs
+3  A: 

You could use Directory.Exists(path) couldn't you?

Dan

Daniel Elliott
+1  A: 
Dim folderItems As String() = Directory.GetFileSystemEntries(aFolder)
Dim someDirItem As String = folderItems(0)
Dim isDirectory As Boolean = System.IO.Directory.Exist(someDirItem)
JDunkerley
+2  A: 

You could create an extension method for enumerations that tests bitwise flags. Something like this:

public static bool Has<T>(this System.Enum type, T value)
{
    try
    {
        return (((int)(object)type & (int)(object)value) == (int)(object)value);
    }
    catch
    {
        return false;
    }
}

Then you would just call:

Bool isDirectory = fInfo.Attributes.Has(FileAttributes.Directory))

Sorry, that's C#, but it shouldn't be hard to convert, I just don't know my VB syntax for generics. Anyone who does, feel free to edit and add the VB translation.

Simon P Stevens
Interesting and more generally applicable solution. Thanks.
Peter Mortensen
This converts C# to VB and vice versa: http://www.developerfusion.com/tools/convert/csharp-to-vb/
dummy
+1  A: 

You don't need to use CInt when performing the comparison:

Dim isDirectory As Boolean = _
    (fInfo.Attributes And FileAttributes.Directory) = FileAttributes.Directory
LukeH
Yes, that is simpler. Thanks.
Peter Mortensen