检查属于文件夹名称

时间:2016-06-01 03:56:22

标签: c# .net file io

我想检查文件夹名称是否包含文件路径。 e.g。

string filePath = @"C:/vietnam/hello/world/welcome.jpg"
IsFileBelongToFolderName(filePath, "hello");//should return true
IsFileBelongToFolderName(filePath, "hell");//should return false

在简单的情况下,我只检查文件路径是否包含“/ FolderName /”,但我不确定它是否适用于任何情况

这项检查是否有任何内置功能?

更新 在实际示例中,我们创建应用程序来同步文件夹。某些子文件夹包含元文件,因此我们不想同步它。

相反传递简单的文件夹名称,我们想要传递子文件夹链,例如:folderName = "hello/world"。我认为它不那么复杂,但与.gitignore文件的工作方式相同。 现在:

string filePath = @"C:/vietnam/hello/world/welcome.jpg"
IsFileBelongToFolderName(filePath, "hello/world");//should return true
IsFileBelongToFolderName(filePath, "hell/world");//should return false
IsFileBelongToFolderName(filePath, "hell");//should return false

4 个答案:

答案 0 :(得分:5)

您可以使用filepath

拆分DirectorySeparatorChar来执行此操作
var directoryPath = Path.GetDirectoryName(filepath);

filePath = Path.GetFullPath(directorypath); // Get Canonical  directory path (Credit to @Aron for pointing this.) 
bool exist = filePath.Split(Path.DirectorySeparatorChar)
                     .Any(x=>x.Equal("hello", StringComparison.InvariantCultureIgnoreCase));

答案 1 :(得分:2)

public bool IsFileBelongToFolderName(string filePath, string folderName)
{
    return filePath.Split('/').Contains(folderName);;
}

public bool IsFileBelongToFolderName(string filePath, string folderName)
{
     return filePath.Split(Path.DirectorySeparatorChar).Any(x=>x.Equal(folderName, StringComparison.InvariantCultureIgnoreCase));
}

答案 2 :(得分:1)

string filePath = @"C:/vietnam/hello/world/welcome.jpg";
            string[] folderNames = filePath.Split('/');
            if(folderNames.Contains("hello"))
            {
                   //folder found
            }

答案 3 :(得分:1)

试试这个

public bool IsFileBelongToFolderName(string filePath, string name){
    return filePath.ToLower().Contains(@"/"+name.ToLower().Replace(@"/", "")+@"/");
}


string filePath = @"C:/vietnam/hello/world/welcome.jpg";

IsFileBelongToFolderName(filePath,"vietnam"); // return True
IsFileBelongToFolderName(filePath,"Vietnam"); // return True
IsFileBelongToFolderName(filePath,"Vietna"); // return false
IsFileBelongToFolderName(filePath,"welcome.jpg"); // return false