0

Example:

File Paths:         | Output:
-----------------------------
C:\Abc\foo.txt      |  true
C:\Abc\foo\bar.txt  |  true
C:\nodir.txt        |  false
E:\nodir.txt        |  false
C:\Abc\             |  true
C:\Abc\def          |  true

How to find if given path contains at least one folder (excluding the main drive folder like C:\) in a given path.

Currently I am thinking to see if I can split by \ and see it contains multiple elements. Is there any elegant solution for this?

RaceBase
  • 18,428
  • 47
  • 141
  • 202
  • If you want to actually check a path rather than parse the string and use File.Exists, take a look at this solution: [How to quickly check if folder is empty (.NET)?](http://stackoverflow.com/a/954837/6741868) – Keyur PATEL Feb 13 '17 at 03:34
  • 2
    Just an FYI, your last two cases are possibly incorrect. You *can* have a folder named 'nodir.txt' – Rob Feb 13 '17 at 03:39
  • @Rob, thanks for pointing out that. I think that can be fixed by checking `FileAttributes.Directory` – RaceBase Feb 13 '17 at 03:46

6 Answers6

2

Another option:

private bool PathHasAtLeastOneFolder(string path)
{
    return Path.GetPathRoot(path).Length < Path.GetDirectoryName(path).Length;
}
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
  • 1
    Succinct, unfortunately fails for the case `E:\Abc`. Unsure if that's a problem for OP, though. – Rob Feb 13 '17 at 03:48
  • If the given path *is* a root drive (i.e. `"C:\"`), the `Path.GetDirectoryName` will return null, causing `.Length` to throw an NRE. – Abion47 Feb 13 '17 at 04:08
1

I hope this will help you :- Directory.GetParent will gives you the Directrory info of the parent folder of the Given path. if its parent is null means it is in the root or else it will be a sub folder under the root.

public bool myMethod(string currentPath)
{
    DirectoryInfo currentParent = Directory.GetParent(@"E:\nodir.txt");
    if (currentParent.Parent != null)
    {
        // if current parent is root means Parent will be null
        return true;
    }
    return false;
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
1

As per my comment, there's no way to be sure for cases like C:\nodir.txt because that could either be a file or a folder.

bool CheckIt(string path)
{
    IEnumerable<string> pathItems = path.Split(Path.DirectorySeparatorChar);

    var isFile = System.IO.File.Exists(path);
    if (isFile)
        pathItems = pathItems.Skip(1);

    if (Path.IsPathRooted(path))
        pathItems = pathItems.Skip(1);

    return pathItems.Any();
}

This will provide the correct answer assuming the paths given actually exist on the system.

If you want it to work regardless of whether or not the files exist, you must make the assumption that a path ending with an extension is a file, not a folder. In that case, you'd update the method with:

var isFile = Path.GetFileNameWithoutExtension(path) != Path.GetFileName(path);
Rob
  • 26,989
  • 16
  • 82
  • 98
  • Yes Rob, I need to fix that by adding `Path is directory or not `. If you add both answers, I can mark it answer so that it will be helpful for other people who might have different choice – RaceBase Feb 13 '17 at 03:47
  • I have updated the question, I want it to work even if file doesn't exist (makes testing easier :)) – RaceBase Feb 13 '17 at 03:59
  • @Reddy The last part of my answer does handle the situation where it doesn't care about the file system, however in that case we do need to make some assumptions – Rob Feb 13 '17 at 04:03
0

This might do the trick for you

if((test.Split('\\').Length - 1)>=2)
{
    //You have more than one folder
}
else
{
    //One file no folder
}

Another idea could be

class Program
{
    static void Main()
    {
        if(TextTool.CountStringOccurrences(Filetest, "\\")>=2)
        {
            //You have more than one folder
        }
        else
        {
            //One file no folder
        }
    }
}

public static class TextTool
{
    public static int CountStringOccurrences(string text, string pattern)
    {
        // Loop through all instances of the string 'text'.
        int count = 0;
        int i = 0;
        while ((i = text.IndexOf(pattern, i)) != -1)
        {
            i += pattern.Length;
            count++;
        }
        return count;
    }
}
Mohit S
  • 13,723
  • 6
  • 34
  • 69
0

Using LINQ to count occurences of the backslash (\) character may be simplest to implement and will yield better performance than Split:

var isRoot = myString.Count(c => c == '\\') > 1;
Serge
  • 3,986
  • 2
  • 17
  • 37
0

You could check if the path's parent is a root drive:

public bool DoesPathContainFolders(string path)
{
    // Double check in case the given path *is* a root drive.
    string parent = Path.GetDirectoryName(path);
    return parent != null && parent != Path.GetPathRoot(path);
}

Or an alternative approach:

public bool DoesPathContainFolders(string path)
{
    // Double check in case the given path *is* a root drive.
    string parent = Path.GetDirectoryName(path);
    return parent != null && Path.GetDirectoryName(parent) != null;
}
Abion47
  • 22,211
  • 4
  • 65
  • 88