C#检查文件是否在目录中的某个级别或以下

C# Check if file is at or below a certain level in directory

我正在 Web 服务器上处理一些文档,如果它们低于层次结构中的某个级别,我需要对它们执行一些操作。例如:

如果结构像 -

example.com/region/site1/
example.com/region/site2/ ...etc...

我只需要对 site1/ 下面的任何文件夹中的文件进行操作(而不是直接在 site1/ 中)

到目前为止我一直在使用这个函数,但我不知道如何使用通配符让 "any folder below this folder" 工作。

public bool isInWorkingDir(string url)
    {
        bool contains = false;
        string lowerUrl = url.ToLower();

        if (lowerUrl.Contains("nor-am/site1/"))
        {
            contains = true;
        }
        return contains;
    }

感谢任何帮助。

谢谢

只需使用 MSDN 文档示例(下页)中的递归 ProcessDirectory 函数。

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

列出文件 = new List();

public static void ProcessDirectory(string targetDirectory) 
{
    // Process the list of files found in the directory.
    string [] fileEntries = Directory.GetFiles(targetDirectory);
    foreach(string fileName in fileEntries)
        ProcessFile(fileName);

    // Recurse into subdirectories of this directory.
    string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
    foreach(string subdirectory in subdirectoryEntries)
        ProcessDirectory(subdirectory);
}

// Insert logic for processing found files here.
public static void ProcessFile(string path)
{
    files.Add(path);        
}

现在用您的基本路径调用 ProcessDirectory,这样您就可以获得该文件夹及其子文件夹中所有文件的列表。然后使用 Linq:

files.Where(f => f.Contains("blabla"));

您基本上可以从 url 中删除文件夹段,并检查剩余路径是否仍包含目录分隔符:

public bool IsNestedUnderSubfolder(string url, string folder)
{
    if (!url.StartsWith(folder))
        return false;

    return url.Substring(folder.Length).Contains("/");
}

// False
IsNestedUnderSubfolder("example.com/region/site1/file.xls", "example.com/region/site1/");

// True
IsNestedUnderSubfolder("example.com/region/site1/folder/file.xls", "example.com/region/site1/");

我的最终代码:

public bool isInWorkingDir(string url)
    {
        bool inDir = false;
        string lowerUrl = url.ToLower();
        if (lowerUrl.Contains("myRegion/mySite") && countSlash(url)>6)
        {
            inDir = true;
        }
        return inDir;
    }
    public int countSlash(string url)
    {
        int length = url.Length;
        int count = 0;
        for (int n = length - 1; n >= 0; n--)
        {
            if (url[n] == '/')
                count++;
        }
        return count;
    }