81

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.

2

8 Answers 8

125

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;
Sign up to request clarification or add additional context in comments.

6 Comments

Just make sure you do this in a try/catch, since the path may not even exist.
What happens if the path has wildcards in it? I get an illegal character argument, but what if I use wildcards and that's a legitimate path for my users?
@MichaelSheely - AFAIK, to deal with wildcards you have to call Directory.GetFiles with the string, and see whether the result has a count greater than zero. A "path with wildcards" isn't a path. It is a pattern.
will not work if path(dir of file) does not exist
@LeresAldtai it is assumed that the path does exist - the OP didn't ask for a check that the path is non-existent.
|
59

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
}

10 Comments

I did not downvote you, but it the accepted answer is surely "simpler" and only needs one call (not two).
The advantage of this approach is that it works even if there is no matching entry in the filesystem at all (in other words, it is neither a folder nor a file); In that sense, it is "simpler". Incidentally, the OP said "a path", and not "a path that is known to exist".
Yeah, I actually think this is the better answer when you're not sure the path you're investigating is there or not. Not having to worry about catching exceptions is a big deal.
I agree that this method is effective. I just created a tiny utility to identify whether the specified name is a file or directory and this method made it extremely simple to return 1 for directory, 2 for file, and 0 for error (e.g., the name is invalid). The tool is tiny (338 bytes source, 3584 bytes compiled) and runs very fast.
@TomPadilla: What exactly would you expect to happen if the path does not exist?
|
11

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.

14 Comments

That seems like allot of work to figure out if a path is a file or directory.
I don't see why this is downvoted, although it would be much simpler to stay in managed code using .NET functionality only.
Introducing Unmanaged code to get if a path is a file or directory is dangerous. I have to relay on the calling function to clean up the memory properly or my code could have leaks.
I still fail to see why this is getting downvoted as it correctly answers the question with a method that provides no level of ambiguitity.
That is the "beauty" of SO, even a good answers might be downvoted by some zealots ;)
|
7

Assuming the directory exists...

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

2 Comments

If path doesn't exist, GetAttributes will return -1.
Docs seem to indicate that it will throw an exception if the file doesn't exist. msdn.microsoft.com/en-us/library/…
4

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

Comments

2

Read the file attributes:

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

Check for the Directory flag.

Comments

1

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.

2 Comments

See 0xA3's answer, slightly better calls imo.
Or just if (Directory.Exists(src)) ... If it's a file, it'll be false. If src is a directory, it'll be false. If src is a directory that doesn't exist, then by definition src can't a directory.
-4

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);

1 Comment

Looking for a .NET solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.