【问题标题】:How to check if path contains at least one folder C#如何检查路径是否包含至少一个文件夹 C#
【发布时间】:2017-06-30 23:28:44
【问题描述】:

例子:

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

如何查找给定路径是否在给定路径中包含至少一个文件夹(excluding the main drive folder like C:\)

目前我正在考虑是否可以按\ 拆分并查看它包含多个元素。有什么优雅的解决方案吗?

【问题讨论】:

  • 如果您想实际检查路径而不是解析字符串并使用 File.Exists,请查看此解决方案:How to quickly check if folder is empty (.NET)?
  • 仅供参考,您的最后两个案例可能不正确。您可以拥有一个名为“nodir.txt”的文件夹
  • @Rob,感谢您指出这一点。我认为这可以通过检查FileAttributes.Directory 来解决

标签: c# file directory


【解决方案1】:

另一种选择:

private bool PathHasAtLeastOneFolder(string path)
{
    return Path.GetPathRoot(path).Length < Path.GetDirectoryName(path).Length;
}

【讨论】:

  • 简洁,不幸的是,E:\Abc 案例失败了。不过,不确定这是否是 OP 的问题。
  • 如果给定路径根驱动器(即"C:\"),Path.GetDirectoryName 将返回 null,导致.Length 抛出 NRE。
【解决方案2】:

根据我的评论,对于C:\nodir.txt 这样的情况,没有办法确定,因为它可能是文件或文件夹。

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();
}

这将提供正确的答案假设给定的路径实际存在于系统中

如果你想让它不管文件是否存在,你必须假设以扩展名结尾的路径是一个文件,而不是一个文件夹。在这种情况下,您可以使用以下方式更新方法:

var isFile = Path.GetFileNameWithoutExtension(path) != Path.GetFileName(path);

【讨论】:

  • 是的 Rob,我需要通过添加 Path is directory or not 来解决这个问题。如果您同时添加两个答案,我可以将其标记为答案,以便对可能有不同选择的其他人有所帮助
  • 我已经更新了问题,即使文件不存在,我也希望它能够工作(使测试更容易:))
  • @Reddy 我回答的最后一部分确实处理了它不关心文件系统的情况,但是在这种情况下,我们确实需要做出一些假设
【解决方案3】:

我希望这会对您有所帮助:- Directory.GetParent 将为您提供给定路径的父文件夹的目录信息。如果它的 parent 为 null 表示它在根目录下,否则它将是根目录下的子文件夹。

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;
}

【讨论】:

    【解决方案4】:

    这可能对你有用

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

    另一个想法可能是

    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;
        }
    }
    

    【讨论】:

      【解决方案5】:

      使用 LINQ 计算反斜杠 (\) 字符的出现次数可能是最简单的实现,并且会产生比 Split 更好的性能:

      var isRoot = myString.Count(c => c == '\\') > 1;
      

      【讨论】:

        【解决方案6】:

        您可以检查路径的父级是否为根驱动器:

        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);
        }
        

        或者另一种方法:

        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;
        }
        

        【讨论】:

          猜你喜欢
          • 2018-07-17
          • 2018-03-21
          • 1970-01-01
          • 2015-07-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-10-02
          • 1970-01-01
          相关资源
          最近更新 更多