【问题标题】:Is there a method to determine if a file path is nested within a directory path in .Net有没有一种方法可以确定文件路径是否嵌套在.Net中的目录路径中
【发布时间】:2011-04-09 06:44:13
【问题描述】:

我想确定一个文件夹是否包含一个文件,当两者都由路径指定时。

乍一看,这似乎很简单。只需检查文件路径是否以目录路径开头。然而,这种幼稚的检查忽略了几个问题:

  • 路径可以是相对的或绝对的
  • 路径可以使用备用目录分隔符
  • 路径可能使用不一致的大小写,这取决于操作系统
  • 不同的路径可能指向同一个位置
  • 可能还有一些我不知道的事情

框架中有没有现成的方法,还是必须自己写?

【问题讨论】:

    标签: .net path filesystems


    【解决方案1】:

    据我所知,没有内置的 .NET 方法可以执行此操作,但以下函数应使用 FileInfo 和 DirectoryInfo 类来完成此操作:

    public static bool FolderContainsFile(String folder, String file)
    {
        //Create FileInfo and DirectoryInfo objects
        FileInfo fileInfo = new FileInfo(file);
        DirectoryInfo dirInfo = new DirectoryInfo(folder);
    
        DirectoryInfo currentDirectory = fileInfo.Directory;
        if (dirInfo.Equals(currentDirectory))
            return true;
    
        while (currentDirectory.Parent != null)
        {
            currentDirectory = currentDirectory.Parent;
    
            if(currentDirectory.Equals(dirInfo)
                return true;
        }
    
        return false;
    
    }
    

    【讨论】:

    • 是的,这会很好地工作(假设没有框架方法)。编辑答案以说明是否存在框架方法,我会接受它。
    【解决方案2】:

    我不确定它是否适用于所有情况,但我建议查看Path.GetFullPath

    引用:返回指定路径字符串的绝对路径。

    【讨论】:

    • GetFullPath 不规范大小写。
    猜你喜欢
    • 1970-01-01
    • 2012-01-21
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 2012-02-09
    • 1970-01-01
    • 2017-10-12
    • 2011-12-25
    相关资源
    最近更新 更多