有没有一种方法,以确定是否嵌套在.net中的目录路径中的文件路径 [英] Is there a method to determine if a file path is nested within a directory path in .Net

查看:103
本文介绍了有没有一种方法,以确定是否嵌套在.net中的目录路径中的文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,以确定是否一个文件夹中包含的文件,当两者都通过的路径指定

I want to determine if a folder contains a file, when both are specified by a path.

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

At first glance this seems simple. Just check if the file path starts with the directory path. However, this naive check ignores several issues:

  • 路径可能是相对或绝对
  • 路径可以使用备用目录分隔符
  • 路径可能使用不一致的外壳,这都和依赖于操作系统
  • 不同的路径可指代相同的位置
  • 在可能更多一些,我不知道

有没有在框架中现有的方法,还是我写我自己?

Is there an existing method in the framework, or do I have to write my own?

推荐答案

据我所知,目前还没有内置的.NET方法要做到这一点,但下面的函数应该使用的FileInfo和DirectoryInfo的类实现这一点:

As far as I know, there is no built-in .NET method to do this, but the following function should accomplish this using the FileInfo and DirectoryInfo classes:

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;

}

这篇关于有没有一种方法,以确定是否嵌套在.net中的目录路径中的文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆