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 FilesMicrosoft Visual Studio 8SDKv2.0Bingacutil.exe
C:Program FilesMicroso…gacutil.exe

Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot