A long way with an ellipse in the middle

I would like to trim a long way to a specific length. However, I want the ellipse in the middle.

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

Is there a standard function or extension method?

+6
source share
3 answers

There is no standard function or extension method, so you have to minimize it yourself.

Check the length and use something like:

 var truncated = ts.Substring(0, 16) + "..." + ts.Substring((ts.Length - 16), 16); 
+4
source

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(); } 
+4
source

It 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; 
+1
source

Source: https://habr.com/ru/post/903205/


All Articles