2011-12-06 17 views
6

Me gustaría truncar una ruta larga a una longitud específica. Sin embargo, quiero tener las elipsis en el medio.Ruta larga con puntos suspensivos en el medio

por ejemplo: \\my\long\path\is\really\long\and\it\needs\to\be\truncated debería convertirse en (truncado a 35 caracteres): \\my\long\path\is...to\be\truncated

¿Hay una función estándar o método de extensión disponible?

+0

Esto también se responde bien en http://stackoverflow.com/questions/8360360/c-sharp-function-to-shrink-file-path-to-be-more-huble-readble –

Respuesta

4

No hay una función estándar o método de extensión, por lo que tendrá que hacer la suya propia.

Compruebe la longitud y utilice algo así como;

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

Aceptado. Tengo un código similar haciendo eso, solo quería hacerlo más limpio. – Vivek

1

Esto funciona

// 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; 
4

Aquí es lo que yo uso. Crea muy bien puntos suspensivos en el medio de un camino y también le permite especificar cualquier longitud o delimitador.

Nota: este es un método de extensión para que pueda usarlo como tal `"c:\path\file.foo".EllipsisString()

Dudo que necesita el bucle while, de hecho, es probable que no, que estaba demasiado ocupado para probar correctamente

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(); 
    } 
Cuestiones relacionadas