Here is what I use. It very beautifully creates an ellipse in the middle of the path, and also allows you to specify any length or separator.
Please note that this is an extension method, so you can use it like so `"c:\path\file.foo".EllipsisString()
I doubt you need a while loop, actually probably not, I'm just too busy to test normally
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(); }
Chris source share