The Microsoft .NET Framework is quite comprehensive, but occasionally an obvious function slips through the cracks and you have to use InteropServices to access the Windows API.
One such obvious miss is the ability to truncate a file path. If you are drawing text and know the font and desired output size, you can use the WinForms TextRenderer class. But to truncate a file path to a specific number of characters, you need the “Shell Lightweight Utility Library” function PathCompactPathEx:
using System.Runtime.InteropServices; [DllImport( "shlwapi.dll" )] static extern bool PathCompactPathEx( [Out] StringBuilder pszOut, string szPath, int cchMax, int dwFlags ); static string TruncatePath( string path, int length ) { StringBuilder sb = new StringBuilder(); PathCompactPathEx( sb, path, length, 0 ); return sb.ToString(); }
For example, here is a file path truncated to 40 characters:
C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe
C:\Program Files\Microso…\gacutil.exe
Copyright © 2007-8 Tiwebb Ltd. All rights reserved. This material may not be published, broadcast, rewritten or redistributed without explicit permission from Tiwebb Ltd.

Hello Timm,
It seems you underestimate the .NET framework a little bit.
Have you ever tried this method TextRenderer.MeasureText?
You can find a detailed description on the MSDN. I reckon it does exactly the trick you mentioned above.
Cheers,
Michael
Hi Michael, thanks for commenting. I should have been more clear. If you are trying to restrict to a size on the screen with a given font, then you can use TextRenderer.MeasureText with TextFormatFlags.PathEllipsis. But if you need to restrict a file path to a specific number of characters, then you need PathCompactPathEx as described in this article.
Hi, although the interop version looks like the viable solution to my problem, I find it un”.NET” way to code. Now, is there an alternate System.Web class for TextRenderer so that I don’t have to reference System.Windows.Forms namespace on my ASPX pages/ web controls? I’m trying to build a custom datagrid with resizable column widths that require this functionality. Any advice will really help me, thanks.
Hi Chris,
The .NET Framework is essentially a collection of classes and methods that wrap interop functions, so it’s certainly not “un-.NET” for you to use interop to access functionality that the .NET designers overlooked. Interop does not introduce any unsafe code, and you’re simply using the tools you need to get the job done.
I’m unaware of a System.Web equivalent of the TextRenderer class. Could you perhaps use the Graphics class DrawString method with a StringFormat argument and StringTrimming enumeration?