Is folder

This is a little helper function to check whether a given path is a folder or a file.

/// <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);
}
Snippet information

Author:
Jonas John

License:
Public domain

Language:
C#

Created:
12/08/2007

Updated:
12/08/2007

Tags:
,



// Define a test path
string filePath = @"C:\Test Folder\";
 
if (IsFolder(filePath)){
    MessageBox.Show("The given path is a folder.");
}
else {
    MessageBox.Show("The given path is a file.");
}

Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

Steve July 11, 2011 at 18:26
Thanks. This saved me some minutes of work.
Olav Alexander Mjelde September 23, 2009 at 09:15
Hi, I dont know how this function is supposed to help?
It wont check if the directory exists properly.

Why not use:
/// <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 (Directory.Exists(path));
}

Then you call it like so:
if (IsFolder(folderBrowserDialog1.SelectedPath))
{
// do something
}
else
{
// do something else
}