How to get relative path from absolute path

前端 未结 23 2213
既然无缘
既然无缘 2020-11-22 11:52

There\'s a part in my apps that displays the file path loaded by the user through OpenFileDialog. It\'s taking up too much space to display the whole path, but I don\'t want

23条回答
  •  一向
    一向 (楼主)
    2020-11-22 12:51

    The function that uses URI returned "almost" relative path. It included directory that directly contains the file which relative path I wanted to get.

    Some time ago I wrote a simple function that returns relative path of folder or file, and even if it's on another drive, it includes the drive letter as well.

    Please take a look:

        public static string GetRelativePath(string BasePath, string AbsolutePath)
        {
            char Separator = Path.DirectorySeparatorChar;
            if (string.IsNullOrWhiteSpace(BasePath)) BasePath = Directory.GetCurrentDirectory();
            var ReturnPath = "";
            var CommonPart = "";
            var BasePathFolders = BasePath.Split(Separator);
            var AbsolutePathFolders = AbsolutePath.Split(Separator);
            var i = 0;
            while (i < BasePathFolders.Length & i < AbsolutePathFolders.Length)
            {
                if (BasePathFolders[i].ToLower() == AbsolutePathFolders[i].ToLower())
                {
                    CommonPart += BasePathFolders[i] + Separator;
                }
                else
                {
                    break;
                }
                i += 1;
            }
            if (CommonPart.Length > 0)
            {
                var parents = BasePath.Substring(CommonPart.Length - 1).Split(Separator);
                foreach (var ParentDir in parents)
                {
                    if (!string.IsNullOrEmpty(ParentDir))
                        ReturnPath += ".." + Separator;
                }
            }
            ReturnPath += AbsolutePath.Substring(CommonPart.Length);
            return ReturnPath;
        }
    

提交回复
热议问题