I'm trying to get the folder position from a given path The path it self is not accessible therefore i cannot use the Directory
nor DirectoryInfo
class Reference post
the result should be something like:
I'm using the following but the result between 1 and 2 is the same :-(:
public static int GetFolderLevelDepth(string fullPath)
{
if(string.IsNullOrEmpty(fullPath))
{
return -99;
}
int result = fullPath.Count(x => x == '\\');
return result -2;
}
Test:
[Test]
public void Get_Level_Root_Depth_Test()
{
var result = StringModifier.GetFolderLevelDepth("c:\\");
Assert.AreEqual(-1,result);
}
[Test]
public void Get_Level_One_Depth_Test()
{
var result = StringModifier.GetFolderLevelDepth("c:\\Folder1");
Assert.AreEqual(0, result);
}
[Test]
public void Get_Level_Two_Depth_Test()
{
var result = StringModifier.GetFolderLevelDepth("c:\\Folder1\\Folder2");
Assert.AreEqual(1, result);
}
This code should account for the most likely input conditions:
int res = -99;
string input = fullPath.Trim();
if (input.Length > 0 && input.Contains(@"\"))
{
if (input.Substring(input.Length - 1, 1) == @"\") input = input.Substring(0, input.Length - 1);
res = input.Split('\\').Length - 2;
}
return res;
fullPath = fullPath.Trim();
if (fullPath[fullPath.Length - 1] != '\\')
return fullPath.Count(x => x == '\\') - 1;
return fullPath.Count(x => x == '\\') - 2;
Or :
return fullPath.Split('\\').Length - 2
You could do something like this instead:
result = fullPath.Split('\\', StringSplitOptions.RemoveEmptyEntries).Length;
StringSplitOptions.RemoveEmptyEntries
causes it to discard the last entry if the path ends with a backslash; which causes the code to not count the "empty directory name" at the end.
Note that this code won't take into account the current directory ( .
) and parent directory ( ..
) special directories, though.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.