Skip to content

January 31, 2010

Shorten a Path String

Here’s a very quick, easy, yet efficient way to take a long path string (for example: “C:\Users\Matt\Documents\Visual Studio 2008\Projects”) and condense it down in VB.NET. Provide a maximum width and a font to measure by, and if the string is longer, part of the string will be replaced with an ellipsis (for example: “C:\Users\Matt\…\Projects”).

LabelSourcePath.Text = ShortenPathString("C:\Users\Matt\Documents\Visual Studio 2008\Projects", LabelSourcePath.Width, LabelSourcePath.Font)

Public Function ShortenPathString(ByVal path As String, ByVal width As Integer, ByVal font As Drawing.Font) As String
    TextRenderer.MeasureText(path, font, New Drawing.Size(width, 0), TextFormatFlags.PathEllipsis Or TextFormatFlags.ModifyString)
    Return path
End Function
Read more from .NET, Development

Share your thoughts, post a comment.

(required)
(required)

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments