Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long path with ellipsis in the middle [duplicate]

Tags:

c#

I would like to truncate a long path to specific length. However, I want to have the ellipsis in the middle.

for example: \\my\long\path\is\really\long\and\it\needs\to\be\truncated should become (truncated to 35 chars): \\my\long\path\is...to\be\truncated

Is there a standard function or extension method available?

like image 457
Vivek Avatar asked Dec 06 '11 16:12

Vivek


3 Answers

There is no standard function or extension method, so you will have to roll your own.

Check for length and use something like;

var truncated = ts.Substring(0, 16) + "..." + ts.Substring((ts.Length - 16), 16);
like image 109
ChrisBint Avatar answered Nov 04 '22 17:11

ChrisBint


Here is what I use. It very nicely create ellipsis in the middle of a path and it also allows you to speciy any length or delimiter.

Note this is an extension method so you can use it like so `"c:\path\file.foo".EllipsisString()

I doubt you need the while loop, in fact you probably don't, I was just too busy to test properly

    public static string EllipsisString(this string rawString, int maxLength = 30, char delimiter = '\\')
    {
        maxLength -= 3; //account for delimiter spacing

        if (rawString.Length <= maxLength)
        {
            return rawString;
        }

        string final = rawString;
        List<string> parts;

        int loops = 0;
        while (loops++ < 100)
        {
            parts = rawString.Split(delimiter).ToList();
            parts.RemoveRange(parts.Count - 1 - loops, loops);
            if (parts.Count == 1)
            {
                return parts.Last();
            }

            parts.Insert(parts.Count - 1, "...");
            final = string.Join(delimiter.ToString(), parts);
            if (final.Length < maxLength)
            {
                return final;
            }
        }

        return rawString.Split(delimiter).ToList().Last();
    }
like image 37
Chris Avatar answered Nov 04 '22 19:11

Chris


This works

    // Specify max width of resulting file name
    const int MAX_WIDTH = 50;

    // Specify long file name
    string fileName = @"A:\LongPath\CanBe\AnyPathYou\SpecifyHere.txt";

    // Find last '\' character
    int i = fileName.LastIndexOf('\\');

    string tokenRight = fileName.Substring(i, fileName.Length - i);
    string tokenCenter = @"\...";
    string tokenLeft = fileName.Substring(0, MAX_WIDTH-(tokenRight.Length + tokenCenter.Length));

    string shortFileName = tokenLeft + tokenCenter + tokenRight;
like image 3
fab Avatar answered Nov 04 '22 17:11

fab