Function to shrink file path to be more human readable

前端 未结 8 765
北海茫月
北海茫月 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 20:54

    You could use something like:

    public string ShrinkPath(string path, int maxLength)
    {
        List parts = new List(path.Split('\\'));
    
        string start = parts[0] + @"\" + parts[1];
        parts.RemoveAt(1);
        parts.RemoveAt(0);
    
        string end = parts[parts.Count-1];
        parts.RemoveAt(parts.Count-1);
    
        parts.Insert(0, "...");
        while(parts.Count > 1 && 
          start.Length + end.Length + parts.Sum(p=>p.Length) + parts.Count > maxLength)
            parts.RemoveAt(parts.Count-1);
    
        string mid = "";
        parts.ForEach(p => mid += p + @"\");
    
        return start+mid+end;
    }
    

    Or just use Olivers solution, which is much easier ;-).

提交回复
热议问题