.NET How to check if path is a file and not a directory?

.NetFileDirectory

.Net Problem Overview


I have a path and I need to determine if it is a directory or file.

Is this the best way to determine if the path is a file?

string file = @"C:\Test\foo.txt";

bool isFile = !System.IO.Directory.Exists(file) && 
                         System.IO.File.Exists(file);

For a directory I would reverse the logic.

string directory = @"C:\Test";

bool isDirectory = System.IO.Directory.Exists(directory) && 
                            !System.IO.File.Exists(directory);

If both don't exists that then I won't go do either branch. So assume they both do exists.

.Net Solutions


Solution 1 - .Net

Use:

System.IO.File.GetAttributes(string path)

and check whether the returned FileAttributes result contains the value FileAttributes.Directory:

bool isDir = (File.GetAttributes(path) & FileAttributes.Directory)
                 == FileAttributes.Directory;

Solution 2 - .Net

I think this is the simplest way where you only need two checks:

string file = @"C:\tmp";
if (System.IO.Directory.Exists(file))
{
    // do stuff when file is an existing directory
}
else if (System.IO.File.Exists(file))
{
    // do stuff when file is an existing file
}

Solution 3 - .Net

You can do this with some interop code:

    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
    [return: MarshalAsAttribute(UnmanagedType.Bool)]
    public static extern bool PathIsDirectory([MarshalAsAttribute(UnmanagedType.LPWStr), In] string pszPath);

To further clarify some of the comments...

Introducing unmanaged code in this is not any more inherintly dangerous than any of the other file or I/O related calls in .NET since they ultimatley all call in to unmanaged code.

This is a single function call using a string. You aren't introducing any new data types and/or memory usage by calling this function. Yes, you do need to rely on the unmanaged code to properly clean up, but you ultimately have that dependency on most of the I/O related calls.

For reference, here is the code to File.GetAttributes(string path) from Reflector:

public static FileAttributes GetAttributes(string path)
{
    string fullPathInternal = Path.GetFullPathInternal(path);
    new FileIOPermission(FileIOPermissionAccess.Read, new string[] { fullPathInternal }, false, false).Demand();
    Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
    int errorCode = FillAttributeInfo(fullPathInternal, ref data, false, true);
    if (errorCode != 0)
    {
        __Error.WinIOError(errorCode, fullPathInternal);
    }
    return (FileAttributes) data.fileAttributes;
}

As you can see, it is also calling in to unmanaged code in order to retrieve the file attributes, so the arguements about introducing unmanaged code being dangerous are invalid. Likewise, the argument about staying completely in managed code. There is no managed code implementation to do this. Even calling File.GetAttributes() as the other answers propose have the same "issues" of calling unmanged code and I believe this is the more reliable method to accomplish determining if a path is a directory.

Edit To answer the comment by @Christian K about CAS. I believe the only reason GetAttributes makes the security demand is because it needs to read the properties of the file so it wants to make sure the calling code has permission to do so. This is not the same as the underlying OS checks (if there are any). You can always create a wrapper function around the P/Invoke call to PathIsDirectory that also demands certain CAS permissions, if necessary.

Solution 4 - .Net

Assuming the directory exists...

bool isDir = (File.GetAttributes(path) & FileAttributes.Directory)
                  == FileAttributes.Directory;

Solution 5 - .Net

Check this out:

/// <summary>
/// Returns true if the given file path is a folder.
/// </summary>
/// <param name="Path">File path</param>
/// <returns>True if a folder</returns>
public bool IsFolder(string path)
{
    return ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory);
}

from http://www.jonasjohn.de/snippets/csharp/is-folder.htm

Solution 6 - .Net

Read the file attributes:

FileAttributes att = System.IO.File.GetAttributes(PATH_TO_FILE);

Check for the Directory flag.

Solution 7 - .Net

Given that a particular path string cannot represent both a directory and a file, then the following works just fine and opens the door for other operations.

bool isFile = new FileInfo(path).Exists;
bool isDir = new DirectoryInfo(path).Exists;

If you're working with the file system, using FileInfo and DirectoryInfo is much simpler than using strings.

Solution 8 - .Net

Hmm, it looks like the Files class (in java.nio) actually has a static isDirectory method. So, I think you could actually use the following:

Path what = ...
boolean isDir = Files.isDirectory(what);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid BasarabView Question on Stackoverflow
Solution 1 - .NetAlnitakView Answer on Stackoverflow
Solution 2 - .NetDirk VollmarView Answer on Stackoverflow
Solution 3 - .NetScott DormanView Answer on Stackoverflow
Solution 4 - .NettvanfossonView Answer on Stackoverflow
Solution 5 - .NetDrorView Answer on Stackoverflow
Solution 6 - .NetIgor ZelayaView Answer on Stackoverflow
Solution 7 - .NetDrew NoakesView Answer on Stackoverflow
Solution 8 - .NetOnikoroshiView Answer on Stackoverflow