Dinesh wakti
Dinesh wakti

Reputation: 135

Check if a folder exists in the filepath

I want to loop through all sub folders and files in a folder and check whether a particular filename contains a folder say "X" in its path (ancestor). I dont want to use string comparison.Is there a better way?

Upvotes: 0

Views: 2584

Answers (3)

Jcl
Jcl

Reputation: 28272

Answering your specific question (the one that is in the title of your question, not in the body), once you have the filename (which other answers tell you how to find), you can do:

bool PathHasFolder(string pathToFileName, string folderToCheck)
{
  return Path.GetDirectoryName(pathToFileName)
             .Split(Path.DirectorySeparatorChar)
             .Any(x => x == folderToCheck);
}

This will work only with absolute paths... if you have relative paths you can complicate it further (this requires the file to actually exist though):

bool PathHasFolder(string pathToFileName, string folderToCheck)
{
  return new FileInfo(pathToFileName)
             .Directory
             .FullName
             .Split(Path.DirectorySeparatorChar)
             .Any(x => x == folderToCheck);
}

Upvotes: 1

Nitro.de
Nitro.de

Reputation: 851

You can use recursive search like

// sourcedir = path where you start searching
public void DirSearch(string sourcedir)
{
    try
    {
        foreach (string dir in Directory.GetDirectories(sourcedir))
        {
            DirSearch(dir);
        }
        // If you're looking for folders and not files take Directory.GetDirectories(string, string)
        foreach (string filepath in Directory.GetFiles(sourcedir, "whatever-file*wildcard-allowed*"))
        {
            // list or sth to hold all pathes where a file/folder was found
            _internalPath.Add(filepath);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
}

So in your case you're looking for folder XYZ, use

// Takes all folders in sourcedir e.g. C:/ that starts with XYZ
foreach (string filepath in Directory.GetDirectories(sourcedir, "XYZ*")){...}

So if you would give sourcedir C:/ it would search in all folders available on C:/ which would take quite a while of course

Upvotes: 0

Oscar
Oscar

Reputation: 13980

You can use Directory.GetFiles()

       // Only get files that begin with the letter "c."
        string[] dirs = Directory.GetFiles(@"c:\", "c*");
        Console.WriteLine("The number of files starting with c is {0}.", dirs.Length);
        foreach (string dir in dirs) 
        {
            Console.WriteLine(dir);
        }

https://msdn.microsoft.com/en-us/library/6ff71z1w(v=vs.110).aspx

Upvotes: 0

Related Questions