.Net - Remove dots from the path

☆樱花仙子☆ 提交于 2019-12-22 01:26:11

问题


How can I convert "c:\foo\..\bar" into "c:\bar"?


回答1:


string path = Path.GetFullPath("C:\\foo\\..\\bar"); // path = "C:\\bar"

More Info




回答2:


Have you tried

string path = Path.GetFullPath(@"C:\foo\..\bar");

in C# using the System.IO.Path class?




回答3:


Use Path.GetFullPath




回答4:


I believe what you're looking for is Syetem.IO.Path as it provides methods to deal with several issues regarding generic paths, even Internet paths.




回答5:


Try System.IO.Path.GetFullPath(@"c:\foo..\bar")




回答6:


I wanted to preserve relative path's without converting them into absolute path, also I wanted to support both - windows and linux style linefeeds (\ or /) - so I've came up with following formula & test application:

using System;
using System.Diagnostics;
using System.Text.RegularExpressions;

class Script
{
    /// <summary>
    /// Simplifies path, by removed upper folder references "folder\.." will be converted
    /// </summary>
    /// <param name="path">Path to simplify</param>
    /// <returns>Related path</returns>
    static String PathSimplify(String path)
    {
        while (true)
        {
            String newPath = new Regex(@"[^\\/]+(?<!\.\.)[\\/]\.\.[\\/]").Replace(path, "" );
            if (newPath == path) break;
            path = newPath;
        }
        return path;
    }


    [STAThread]
    static public void Main(string[] args)
    {
        Debug.Assert(PathSimplify("x/x/../../xx/bbb") == "xx/bbb");
        // Not a valid path reference, don't do anything.
        Debug.Assert(PathSimplify(@"C:\X\\..\y") == @"C:\X\\..\y");
        Debug.Assert(PathSimplify(@"C:\X\..\yy") == @"C:\yy");
        Debug.Assert(PathSimplify(@"C:\X\..\y") == @"C:\y");
        Debug.Assert(PathSimplify(@"c:\somefolder\") == @"c:\somefolder\");
        Debug.Assert(PathSimplify(@"c:\somefolder\..\otherfolder") == @"c:\otherfolder");
        Debug.Assert(PathSimplify("aaa/bbb") == "aaa/bbb");
    }
}

Remove extra upper folder references if any




回答7:


Not a direct answer, but from the question I suspect you are trying to reinvent the System.IO.Path.Combine() method. That should eliminate the need to create paths like the one you are asking about overall.




回答8:


In case you want to do this yourself, you may use this code:

var normalizePathRegex = new Regex(@"\[^\]+\..");
var path = @"C:\lorem\..\ipsum"
var result = normalizePathRegex.Replace(unnormalizedPath, x => string.Empty);

URLs and UNIX-style paths:

var normalizePathRegex = new Regex(@"/[^/]+/..");
var path = @"/lorem/../ipsum"
var result = normalizePathRegex.Replace(unnormalizedPath, x => string.Empty);

Note: Remember to use RegexOptions.Compiled when utilizing this code in a real-world application



来源:https://stackoverflow.com/questions/970911/net-remove-dots-from-the-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!