Adding ellipsis to directory path

Before I start writing code, does anyone know if there's a method buried in one of the .NET classes to convert a directory path to one with ellipsis I thought there was, but I haven't been able to find any references to it.

I need to display a directory path in a label control, and setting the "Allow ellipses" in the label control only adds the ellipses to the end of the string.

TIA,

Richard



Answer this question

Adding ellipsis to directory path

  • perun

    Whoops, talked too soon. This code throws an exception on short paths. Here is a better example:
    string path = <whatever>
    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path );
    if (dir != null)
    {
    string directParent = string.Empty;
    string parentParent = string.Empty;
    string rootDir = string.Empty;
    string ellipsis = "...";
    System.IO.DirectoryInfo p = dir.Parent;
    if ((p != null) && (p.Name != dir.Root.Name))
    {
    directParent = p.Name + @"\";
    System.IO.DirectoryInfo pp = p.Parent;
    if ((pp != null) && (pp.Name != dir.Root.Name))
    {
    parentParent = pp.Name + @"\";
    }
    else
    {
    ellipsis = string.Empty;
    }
    }
    else
    {
    ellipsis = string.Empty;
    }
    pathList.Add(dir.Root.Name + ellipsis + parentParent + directParent + dir.Name);
    }
    else
    {
    Console.Writeline("Foobar");
    }

  • Tom Amsden

    I needed the same thing, but I believe that going the OnPaint route introduces a whole world of complexity. Here is some trivial code to make your own path ellipsis:

    string path = <whatever>;

    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path);

    string ellipsisPath = dir.Root.Name + "..." + @"\" + dir.Parent.Parent.Name + @"\" + dir.Parent.Name + @"\" + dir.Name;

    This is probably too late to help you, but maybe someone else will benefit.


  • wadleys

    The enumerated StringTrimming property of the StringFormat object passed to the Graphics.DrawString method have the following choices which may be applicable to your situation:

    • EllipsisCharacter: Specifies that the text is trimmed to the nearest character, and an ellipsis is inserted at the end of a trimmed line.
    • EllipsisPath: The center is removed from trimmed lines and replaced by an ellipsis. The algorithm keeps as much of the last slash-delimited segment of the line as possible.
    • EllipsisWord: Specifies that text is trimmed to the nearest word, and an ellipsis is inserted at the end of a trimmed line.

    If you are able to override the Paint method for your label, you might be able to draw the label text to suit your situation. Hope this info helps.


  • Adding ellipsis to directory path