簡體   English   中英

如何比較C#中的相對文件或目錄路徑?

[英]How do I compare relative file or directory paths in C#?

關於C#中文件路徑的比較已經存在一個問題 但提供的解決方案意味着我有絕對的路徑。 任何人都可以建議一個良好的相對路徑解決方案或指向我在比較路徑時必須注意的事情(在Windows上)。

例如:

  • share/logs
  • share\\logs
  • share/logs\\

那些字符串意味着相同的路徑

您在帖子中鏈接的答案實際上適合您。 GetFullPath不僅解析絕對路徑的完整路徑,還解析絕對路徑的相對路徑。 只是不要忘記使用鏈接答案中提供的代碼來解決尾部斜杠並添加代碼來替換/\\ (如Henk所述)

正如Henk指出的那樣,在某些情況下可能必須首先清理路徑(或拒絕作為有效路徑)。 頁面描述有效的文件和路徑名稱。 您可能希望在使用以下內容進行比較之前清理路徑:

string FormatPath(string path){
    string result = path.Replace("/","\\");
    result = result.TrimStart("\\");
    return result;
}

通過查看DirectoryInfo API Reference,以下內容應該可以正常工作:

DirectoryInfo d1 = new DirectoryInfo(FormatPath("share/logs")));
DirectoryInfo d2 = new DirectoryInfo(FormatPath("share\logs")));

if(d1.FullName.Equals(d2.FullName)){
    // They are the same
}

基本上只是從相對路徑中提取絕對路徑,並在絕對路徑上進行比較。

我認為,不是真的了解你的問題,但是:

你將如何比較他們?

  1. 系統中的所有路徑都具有相同的唯一根,沒有子路徑。 只是比較可比較的路徑字符串是否相等(在路徑格式之前統一,我的意思是'/''\\'符號)。 不太好的解決方案,因為有一天你或經理可能希望有嵌套的路徑,你的解決方案將被制動。

  2. 只需弄清楚完整路徑並按照鏈接中提供的解決方案。

您應該嘗試此問題中提出的解決方案: 如何在C#中比較(目錄)路徑?

Path.GetFullPath()可以將相對路徑作為參數: http//msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx

這段代碼規范化路徑(包括相對路徑)。 一旦路徑被規范化,(不區分大小寫)字符串比較就等同於路徑比較。

這個特定的實現不假設“/”等於“\\”,但你可以通過在將字符串傳遞給此方法之前替換“/”來輕松解決這個問題....

/// <summary>
///     Converts a path in a form suitable for comparison with other paths.
/// </summary>
/// <remarks>
///     <para>
///         In general case, two equivalent paths do not necessarily have the same string
///         representation. However, after subjecting them to this method, they will have
///         (case-insensitively) equal string representations.
///     </para>
///     <para>
///         Removes ".." and "." and always trims trailing path separator (except for paths
///         in format "X:\" or "\"). Does not change case.
///     </para>
///     <para>
///         This method does not attempt to validate the path (since its purpose is only to
///         make paths comparable as strings), so some logically incorrect paths will pass
///         through it unscathed. Examples of such paths include: "C:\..", "\..",
///         "\\machine\c$\..", "\\machine\c$\..\.." etc...
///     </para>
/// </remarks>
/// <returns>
///     Normalized path. Empty or <c>null</c> <paramref name="path"/> results in empty or
///     <c>null</c> result.
/// </returns>
/// <seealso cref="PathComparer"/>
public static string NormalizePath(string path) {

    if (string.IsNullOrEmpty(path))
        return path;

    // Remove path root.
    string path_root = Path.GetPathRoot(path);
    path = path.Substring(path_root.Length);

    string[] path_components = path.Split(Path.DirectorySeparatorChar);

    // "Operating memory" for construction of normalized path.
    // Top element is the last path component. Bottom of the stack is first path component.
    Stack<string> stack = new Stack<string>(path_components.Length);

    foreach (string path_component in path_components) {

        if (path_component.Length == 0)
            continue;

        if (path_component == ".")
            continue;

        if (path_component == ".." && stack.Count > 0 && stack.Peek() != "..") {
            stack.Pop();
            continue;
        }

        stack.Push(path_component);

    }

    string result = string.Join(new string(Path.DirectorySeparatorChar, 1), stack.Reverse().ToArray());
    result = Path.Combine(path_root, result);

    return result;

}

你可能想看看Uri班及其成員。 有用於組合和比較相對路徑存在的方法,而且也使用MakeRelativeUri的簡短實例這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM