看看文件路径的目录里面 [英] See if file path is inside a directory

查看:119
本文介绍了看看文件路径的目录里面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何检查是否一个路径,这并不必然存在指向一个位置的特定目录中的文件?说我有一个方法:

 布尔IsInside(路径字符串,字符串的文件夹)
{
    // ...
}
 

然后,如果我把它想:

  IsInside(C:\\用户\\ \\花花公子喜,C:\\用户\\ \\花花公子喜\\ \\的子文件夹\\ SubSubFolder瓦。 TXT)
 

应该返回(注意子文件夹),但如果我把它想:

  IsInside(C:\\用户\\ \\花花公子喜,C:\\用户\\ \\花花公子\\ BadFolder子文件夹\\ SubSubFolder \\瓦。 TXT)
 

应该返回false。我唯一​​能想到的,现在是一个使用字符串的 StartsWith ,但听起来有点哈克给我。我还没有找到一个本地.NET方法要么检查。

解决方案

您可以尝试的 string.IndexOf 方法。如果您使用超载用的 StringComparison枚举它应该给你你需要的结果。

从上面的链接:

  

报告中第一次出现的一个或多个字符或字符串的第一次出现的从零开始的索引,这个字符串中。该方法返回-1,如果字符或字符串未在此实例中找到。

 布尔IsInside(字符串的文件夹,路径字符串)
{
   如果(path.IndexOf(文件夹,StringComparison.OrdinalIgnoreCase)!=  -  1)
        返回true;
    其他
        返回false;
 

How can I check whether a path to a file that doesn't necessarily exists points to a location inside a particular directory? Say I have a method:

bool IsInside(string path, string folder)
{
    //...
}

Then, if I call it like:

IsInside("C:\\Users\\Dude\\Hi", "C:\\Users\\Dude\\Hi\\SubFolder\\SubSubFolder\\tile.txt")

should return true (note the sub folder), but if I call it like:

IsInside("C:\\Users\\Dude\\Hi", "C:\\Users\\Dude\\BadFolder\\SubFolder\\SubSubFolder\\tile.txt")

should return false. The only thing I can think of right now is using string's StartsWith, but sounds kinda hacky to me. I haven't found a native .NET method that would check this either.

解决方案

You could try the string.IndexOf method. If you use the overload with the StringComparison enumeration it should give you the result you need.

From above link:

Reports the zero-based index of the first occurrence of one or more characters, or the first occurrence of a string, within this string. The method returns -1 if the character or string is not found in this instance.

bool IsInside(string folder, string path)
{
   if (path.IndexOf(folder,StringComparison.OrdinalIgnoreCase) != -1)
        return true;
    else
        return false;    

这篇关于看看文件路径的目录里面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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