Function to shrink file path to be more human readable

前端 未结 8 713
北海茫月
北海茫月 2020-12-31 20:15

Is there any function in c# to shink a file path ?

Input: \"c:\\users\\Windows\\Downloaded Program Files\\Folder\\Inside\\example\\file.txt\"

<
相关标签:
8条回答
  • 2020-12-31 21:11

    If you want to write you own solution to this problem, use build in classes like: FileInfo, Directory, etc... which makes it less error prone.

    The following code produces "VS style" shortened path like: "C:\...\Folder\File.ext".

    public static class PathFormatter
    {
        public static string ShrinkPath(string absolutePath, int limit, string spacer = "…")
        {
            if (string.IsNullOrWhiteSpace(absolutePath))
            {
                return string.Empty;
            }
            if (absolutePath.Length <= limit)
            {
                return absolutePath;
            }
    
            var parts = new List<string>();
    
            var fi = new FileInfo(absolutePath);
            string drive = Path.GetPathRoot(fi.FullName);
    
            parts.Add(drive.TrimEnd('\\'));
            parts.Add(spacer);
            parts.Add(fi.Name);
    
            var ret = string.Join("\\", parts);
            var dir = fi.Directory;
    
            while (ret.Length < limit && dir != null)
            {
                if (ret.Length + dir.Name.Length > limit)
                {
                    break;
                }
    
                parts.Insert(2, dir.Name);
    
                dir = dir.Parent;
                ret = string.Join("\\", parts);
            }
    
            return ret;
        }
    }
    
    0 讨论(0)
  • 2020-12-31 21:14

    Jeff Atwood posted a solution to this on his blog and here it is :

    [DllImport("shlwapi.dll", CharSet = CharSet.Auto)]
    static extern bool PathCompactPathEx([Out] StringBuilder pszOut, string szPath, int cchMax, int dwFlags);
    
    static string PathShortener(string path, int length)
    {
        StringBuilder sb = new StringBuilder();
        PathCompactPathEx(sb, path, length, 0);
        return sb.ToString();
    }
    

    It uses the unmanaged function PathCompactPathEx to achieve what you want.

    0 讨论(0)
提交回复
热议问题