0

Given a path (that may be relative), how am I able to check if the path is a directory, or a guid, or a file. They might not exist which is what is making it difficult for me to figure out a solution to.

My previous solution was to check if the path was an extension like so:

    public bool IsDirectory(string path)
    {
        var extension = Path.GetExtension(path);

        return string.IsNullOrEmpty(extension);
    }

But I discovered that this path will commonly also be a path to a guid, so the above will be incorrect.

Is there a better way I can write a function to check all these cases?

Greg
  • 187
  • 3
  • 15
  • 3
    `check if the path is a directory, or a guid, or a file` one of these things is not like the others – Jonesopolis Nov 04 '16 at 14:11
  • 1
    Are you saying that sometimes you have file names that are just Guids without an extension? Because a path is either to a file or a directory and it's not clear how Guids are related to your paths. – juharr Nov 04 '16 at 14:12
  • 1
    This link may help you: [http://stackoverflow.com/questions/1395205/better-way-to-check-if-a-path-is-a-file-or-a-directory](http://stackoverflow.com/questions/1395205/better-way-to-check-if-a-path-is-a-file-or-a-directory) – Kymuweb Nov 04 '16 at 14:12
  • This guid thing is confuse, it will be just a guid by itself or a folder/file named after a guid? – Paulo Junior Nov 04 '16 at 14:12
  • @juharr yes that is what I'm saying apologies for not being clear – Greg Nov 04 '16 at 14:14
  • 1
    In that case the question that @Kymuweb linked will give you a solution, though you need to make sure your path is relative to the current working directory. – juharr Nov 04 '16 at 14:15
  • @Paulo/Jonesopolis it can be a guid by itself – Greg Nov 04 '16 at 14:15
  • @Kyumweb thank you I will check that out – Greg Nov 04 '16 at 14:16
  • It's impossible to tell if a non-existent path would be a file or a directory. – airafr Nov 04 '16 at 14:24

1 Answers1

3

This will check if its a file or a path first, if it is not we try to parse it for a guid.

if(File.Exists(path))
{
    FileAttributes attr = File.GetAttributes(path);

    if (attr.HasFlag(FileAttributes.Directory))
        MessageBox.Show("Its a directory");
    else
        MessageBox.Show("Its a file");
}
else
{
    Guid guid;

    if (Guid.TryParse(path, out guid))
        MessageBox.Show("Its a Guid");
}
Paulo Junior
  • 266
  • 2
  • 8