[英]Getting the relative path from the full path
我必須得到路徑,不包括完整路徑的相對路徑
相對路徑是, C:\\ User \\ Documents \\
fullpath, C:\\ User \\ Documents \\ Test \\ Folder2 \\ test.pdf
我想只得到相對路徑之后的路徑,即\\ Test \\ Folder2 \\ test.pdf
我怎樣才能做到這一點。
我使用C#作為編程語言
你不是在談論親戚,所以我稱之為部分路徑。 如果你可以確定部分路徑是完整路徑的一部分,那么它就是一個簡單的字符串操作:
string fullPath = @"C:\User\Documents\Test\Folder2\test.pdf";
string partialPath = @"C:\User\Documents\";
string resultingPath = fullPath.Substring(partialPath.Length);
這需要一些錯誤檢查 - 當fullPath或partialPath為null或兩個路徑具有相同的長度時,它將失敗。
嗯,但如果情況有所不同呢? 或者其中一個路徑為其文件夾使用短名稱? 更完整的解決方案將是......
public static string GetRelativePath(string fullPath, string containingFolder,
bool mustBeInContainingFolder = false)
{
var file = new Uri(fullPath);
if (containingFolder[containingFolder.Length - 1] != Path.DirectorySeparatorChar)
containingFolder += Path.DirectorySeparatorChar;
var folder = new Uri(containingFolder); // Must end in a slash to indicate folder
var relativePath =
Uri.UnescapeDataString(
folder.MakeRelativeUri(file)
.ToString()
.Replace('/', Path.DirectorySeparatorChar)
);
if (mustBeInContainingFolder && relativePath.IndexOf("..") == 0)
return null;
return relativePath;
}
要擴展Jan的答案,您可以在string
類(或Path
類,如果需要)上創建擴展方法,例如:
namespace ExtensionMethods
{
public static class MyExtensions
{
public static string GetPartialPath(this string fullPath, string partialPath)
{
return fullPath.Substring(partialPath.Length)
}
}
}
然后使用:
using ExtensionMethods;
string resultingPath = string.GetPartialPath(partialPath);
我沒有測試過這種擴展方法是否有效,但是應該這樣做 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.