rulururu

post Shorten a Path

June 25th, 2008

Filed under: .NET — Kai @ 7:36 pm

Sometimes you need a long path to be short because the field that displays the text doesn’t have enought space for the whole path.

This in .NET written function does cut “C:\Windows\System32\Test\Test.dll” to “C:\Windows\…\Test.dll”.

First parameter is the path that has to be shorten.
Second parameter is the maximum length of the new string.
Third parameter is the Font that is used.
Return value is the new storten string.

public string PathShorten(string Path, int Length, Font TextFont)
{
    string[] PathParts = Path.Split('\\');
    StringBuilder PathBuild = new StringBuilder(Path.Length);
    string LastPart = PathParts[PathParts.Length - 1];
    string PrevPath = "";
 
    //check if path is already shorter than max. length
    if (TextRenderer.MeasureText(Path, TextFont).Width < Length)
        return Path;
 
    for (int i = 0; i < PathParts.Length - 1; i++)
    {
        PathBuild.Append(PathParts[i] + @"\");
        if (TextRenderer.MeasureText(PathBuild.ToString() + @"...\" 
              + LastPart, TextFont).Width >= Length)
            return PrevPath;
        else
            PrevPath = PathBuild.ToString() + @"...\" + LastPart;
    }
    return PrevPath;
}

Just a simple snipped but I guess that it can often be valuable. I hope it can be used widely.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

ruldrurd
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)