Function to shrink file path to be more human readable

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

    I was just faced with this issue as long paths were becoming a complete eye sore. Here is what I tossed together real quick (mind the sloppiness) but it gets the job done.

    private string ShortenPath(string path, int maxLength)
    {
        int pathLength = path.Length;
    
        string[] parts;
        parts = label1.Text.Split('\\');
    
        int startIndex = (parts.Length - 1) / 2;
        int index = startIndex;
    
        string output = "";
        output = String.Join("\\", parts, 0, parts.Length);
    
        decimal step = 0;
        int lean = 1;
    
        do
        {
            parts[index] = "...";
    
            output = String.Join("\\", parts, 0, parts.Length);
    
            step = step + 0.5M;
            lean = lean * -1;
    
            index = startIndex + ((int)step * lean);
        }
        while (output.Length >= maxLength && index != -1);
    
        return output;
    }
    

    Results

    EDIT

    Below is an update with Merlin2001's corrections.

    private string ShortenPath(string path, int maxLength)
    {
        int pathLength = path.Length;
    
        string[] parts;
        parts = path.Split('\\');
    
        int startIndex = (parts.Length - 1) / 2;
        int index = startIndex;
    
        String output = "";
        output = String.Join("\\", parts, 0, parts.Length);
    
        decimal step = 0;
        int lean = 1;
    
        while (output.Length >= maxLength && index != 0 && index != -1)
        {
            parts[index] = "...";
    
            output = String.Join("\\", parts, 0, parts.Length);
    
            step = step + 0.5M;
            lean = lean * -1;
    
            index = startIndex + ((int)step * lean);
        }
        // result can be longer than maxLength
        return output.Substring(0, Math.Min(maxLength, output.Length));  
    }
    

提交回复
热议问题