Function to shrink file path to be more human readable

前端 未结 8 781
北海茫月
北海茫月 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:59

    If you want do insert ellipsis dependent on the length of the path string, then use this code:

    TextRenderer.MeasureText(path, Font, 
        new System.Drawing.Size(Width, 0),
        TextFormatFlags.PathEllipsis | TextFormatFlags.ModifyString);
    

    It will modify path in-place.

    EDIT: Be careful with this method. It breaks the rule, saying that strings in .NET are immutable. In fact, the first parameter of the MeasureText method is not a ref parameter, which means that no new string can be returned. Instead, the existing string is altered. It would be careful to work on a copy created with

    string temp = String.Copy(path);
    

提交回复
热议问题