Click here to Skip to main content
11,413,548 members (66,745 online)
Click here to Skip to main content

Use the .NET framework to shorten a path string with an ellipsis

, 8 Apr 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
Compact a path or any string using built in .NET framework API


Remember the Windows API PathCompactPath[Ex] used to take a path and shorten it by inserting an ellipsis in the appropriate place to make it fit a specific pixel width? Ever wonder how to do it native .NET? There's a very simple way to do it with the TextRenderer.MeasureText method but it's relatively undocumented.


If you're familiar with this problem you might already know about using Windows.Forms.TextRenderer.DrawText or Drawing.Graphics.DrawString methods to programmatically draw a shortened string using the framework. But I wanted a way to retrieve a shortened string in memory to later use that string inside an existing control (like a menu item).

Using the Code

Here's a simple function to do the trick, internally I copy the string (to keep it from affecting the source string), call Windows.Forms.TextRenderer.MeasureText with the magic bitwise parameter: TextFormatFlags.ModifyString, and return the string variable that was passed into the function.

Function CompactString(ByVal MyString As String, ByVal Width As Integer,
    ByVal Font As Drawing.Font,
    ByVal FormatFlags As Windows.Forms.TextFormatFlags) As String

Dim Result As String = String.Copy(MyString)

TextRenderer.MeasureText(Result, Font, New Drawing.Size(Width, 0),
    FormatFlags Or TextFormatFlags.ModifyString)

Return Result

End Function

To set a label to a compacted version of the string path you would call:

Label1.Text = CompactString(MyPath, Label1.Width, Label1.Font,

For example, the string: c:\program files\test app\runme.exe might turn into:

c:\program files\...\runme.exe depending on the font and width.

Check out the Windows.Forms.TextFormatFlags enumerated type for other options on how to compact your string. TextFormatFlags.WordEllipsis for example will insert a "..." at the end of the string instead in between parts of a path.

Points of Interest

You might be thinking, why not just write your own algorithm to break apart a string and insert the ellipsis in a certain spot. And in fact I have seen programmers doing this but I would recommend using the framework to handle this for a couple reasons:

  1. Why reinvent the wheel? Microsoft already did it and it's probably well tested and efficient; do you really have extra time on your hands?
  2. What if the standard for where to put the ellipsis changes? Maybe someday the ellipsis will be commonly inserted just after the drive letter instead of just before the filename. Let MS think about these details and just follow their lead. If MS changes this implementation internally, your app will automatically follow suit.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Tim Greenfield
Software Developer (Senior)
United States United States
I am a software architect and engineer who has been working in the industry since 1994. Although I officially started writing software many years earlier at age 11 by authoring games, graphics demos, or whatever I found interesting. I even landed my first consulting job at age 16 implementing a newly invented mathimatical algorithm for a team of researchers at the local University.

I've designed and implemented hundreds if not thousands of applications: client, web, and hybrid of all scales and was a contributing author to the Black Belt programming column of Visual Basic Programmer's Journal.

My goals when coding are always to write clean, reusable and optimized code using the latest and technology, tools and techniques.

Comments and Discussions

GeneralMy vote of 5 Pin
JohnPap_CP, 6-Apr-11 6:52
memberJohnPap_CP6-Apr-11 6:52 
QuestionHow about WPF? Pin
GLLNS, 18-May-09 9:51
memberGLLNS18-May-09 9:51 
GeneralMore Information Pin
Andy Missico, 26-Feb-09 16:51
memberAndy Missico26-Feb-09 16:51 
GeneralStrange Behavior Pin
cjbarth, 9-Jan-09 11:59
membercjbarth9-Jan-09 11:59 
When I run this code as it is and use it to change the Text attribute of a check box it runs a little long. That is easily fixed by reducing the width of the field by 22 when calling the function.

Another problem that I had with this setup is that I would get a string returned with the exact same length as the original string, which would then be written to the check box text label as c:\this\is\...\test[]a\very\long, where [] is that box character that means that there is no glyph to represent the character in the string. I stepped through the string character by character and found that the [] character was Nothing, literally, when I assigned the [] to a Char type it was reported as Nothing. So I had to include the following code in my path shrinking routine to catch this Nothing and get rid of it and everything after it.

    Public Function ShrinkString(ByVal strString As String, ByVal intWidth As Integer, ByVal Font As Drawing.Font, ByVal FormatFlags As Windows.Forms.TextFormatFlags) As String
        Dim strWorking As String = String.Copy(strString)
        Dim strResult As String = ""
        Dim charResult As Char = ""
        TextRenderer.MeasureText(strWorking, Font, New Drawing.Size(intWidth, 0), FormatFlags Or TextFormatFlags.ModifyString)
        For Each charResult In strWorking
            If charResult = Nothing Then
                Exit For
            End If
            strResult &= charResult
        Return strResult
    End Function

If you want to see this Nothing character, step through this code and watch charResult in the Locals window. You'll also notice that the strWorking doesn't have a " on the end of it.

I'm in VS2005 using a .Net 2.0 program.

Chris Barth
QuestionHow can we get the modified string? Pin
Waleed Eissa, 5-Sep-08 20:10
memberWaleed Eissa5-Sep-08 20:10 
GeneralThis code will fail with AccessViolationException Pin
Eugene Sichkar, 23-Jun-08 14:44
memberEugene Sichkar23-Jun-08 14:44 
GeneralTruncate to null Pin
Don Kackman, 11-Nov-07 4:03
memberDon Kackman11-Nov-07 4:03 
Questionshorten path for recent files Pin
Zach1981, 23-Oct-07 2:52
memberZach198123-Oct-07 2:52 
AnswerRe: shorten path for recent files Pin, 15-Jul-08 3:32
memberchr.dev15-Jul-08 3:32 
GeneralRemoved from .NET 3.0 Pin
RichardCollins2, 24-May-07 23:58
memberRichardCollins224-May-07 23:58 
GeneralRe: Removed from .NET 3.0 Pin
Greg Osborne, 8-Jan-09 6:37
memberGreg Osborne8-Jan-09 6:37 
QuestionCopy? Pin
Nchantim, 10-Apr-07 8:11
memberNchantim10-Apr-07 8:11 
AnswerRe: Copy? Pin
Nchantim, 10-Apr-07 8:24
memberNchantim10-Apr-07 8:24 
GeneralRe: Copy? Pin
Tim Greenfield, 12-Apr-07 6:06
memberTim Greenfield12-Apr-07 6:06 
GeneralRe: Copy? Pin
RichardCollins2, 20-May-07 23:55
memberRichardCollins220-May-07 23:55 
GeneralNice Pin
Patrick Sears, 8-Apr-07 15:24
memberPatrick Sears8-Apr-07 15:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150427.1 | Last Updated 8 Apr 2007
Article Copyright 2007 by Tim Greenfield
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid