How to check if a String Path is a 'File' or 'Directory' if path doesn't exist?

c# io
13,618

Solution 1

If files in your scenario must have extensions then you could use this method.

NOTE: It is legal in windows to have periods in directories, but this was mostly introduced for cross operating system compatibility of files. In strictly windows environments it is considered bad form to have files without extensions or to put periods or spaces in directory names. If you do not need to account for that scenario then you could use this method. If not you would have to have some sort of flag sent through the chain or a structure to identify the intent of the string.

var ext = System.IO.Path.GetExtension(strPath);
if(ext == String.Empty)
{
    //Its a path
}

If you do not need to do any analysis on file type you can go as simple as:

if(System.IO.Path.HasExtension(strPath))
{
    //It is a file
}

Solution 2

The short answer is that there is no 100% way to distinguish a folder from a file by path alone. A file does not have to have a file extension, and a folder can have periods in its name (making it look like a file extension).

Share:
13,618
Enumy
Author by

Enumy

Updated on June 06, 2022

Comments

  • Enumy
    Enumy almost 2 years

    I have a function that automatically creates a specified Path by determining whether the String Path is a File or Directory.

    Normally, i would use this if the path already exists:

    FileAttributes attributes = File.GetAttributes("//Path");
    
    if ((attributes & FileAttributes.Directory) == FileAttributes.Directory)
        {
            Directory.CreateDirectory("//Path");
        }
    

    But what if it doesn't? How to check whether the String Path is a File or Directory if it doesn't exist?

  • Enumy
    Enumy over 9 years
    A little modification to be Boolean Extention = System.IO.Path.HasExtension("//Path")
  • Alexei Levenkov
    Alexei Levenkov over 9 years
    +0: Note: while this approach may work for OP it is wrong: there is no restrictions on folder names to not include dot. It is perfectly ok to have folder named "MyImages.jpg" or "Game.Saves".
  • Enumy
    Enumy over 9 years
    @AlexeiLevenkov This was needed for the Application usage and not involving the Userand as for, it is not possible for the a Directory to include an Extension signature
  • Carter
    Carter over 9 years
    @AlexeiLevenkov Your point is moot though. System.IO.Path.GetExtension is smart enough to start from the end of the string and identify if there is an extensions before the first directory separator. If your files must have extensions this method works fine.
  • Ariex
    Ariex over 8 years
    this method will not work if a file have no extension