问题描述
假设我有以下路径和基本目录
string FileDirectory = "/tmp/simple";
string fullPath = "/tmp/simple/s1/s1.txt";
那么如何在不写循环的情况下找到s1.txt
相对于FileDirectory
的路径?
即;我想要 s1/s1.txt
作为输出。
这看起来与 Substring 操作相反。
所以我喜欢
string relativePath = fullPath.Substring(FileDirectory.Length,(fullPath.Length - FileDirectory.Length));
解决方法
我认为您正在寻找 Path.GetRelativePath(...)
。像这样使用:
string FileDirectory = "/tmp/simple";
string fullPath = "/tmp/simple/s1/s1.txt";
string result = Path.GetRelativePath(FileDirectory,fullPath);
// s1\s1.txt
要使用正斜杠 /
获得结果,您可以对结果执行简单的 Replace()
:
result = result.Replace("\\","/");
// s1/s1.txt