检查属于文件夹名称的文件路径
问题描述:
我想检查文件夹名是否包含文件路径。 例如检查属于文件夹名称的文件路径
string filePath = @"C:/vietnam/hello/world/welcome.jpg"
IsFileBelongToFolderName(filePath, "hello");//should return true
IsFileBelongToFolderName(filePath, "hell");//should return false
在简单的情况下,我只检查文件路径包含“/文件夹名/”,但我不知道它是任何情况下
确实有此检查任何内置的功能是否正确?
UPDATE 在实际的例子中,我们创建应用程序来同步文件夹。某些子文件夹包含元文件,因此我们不想同步它。
改为传递简单文件夹名称,我们要传递子文件夹链,例如: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
答
您可以通过使用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));
答
string filePath = @"C:/vietnam/hello/world/welcome.jpg";
string[] folderNames = filePath.Split('/');
if(folderNames.Contains("hello"))
{
//folder found
}
答
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));
}
答
试试这个
分裂filepath
做到这一点
public bool IsFileBelongToFolderName(string filePath, string name){
return filePath.ToLower().Contains(@"/"+name.ToLower().Replace(@"/", "")[email protected]"/");
}
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
您应该首先对路径进行规范化。例如'c:\ foo \ bar \ baz.txt'属于'c:\ foo \ bar \ qux \ .. \'。 – Aron
@Aron这是一个有效的点,现在更新它。谢谢。 –
你应该首先排除文件名,如果folderName =“welcome.jpg” – phuongnd