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?
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);
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();
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With