Need to truncate a Path, and show the compacted path in a edit control?

By [)ia6l0 iii
Access over 40 UI widgets with everything from interactive menus to rich charts.

At times, we need to truncate a path by certain characters and fit it in a edit control, so that it looks like an exact fit. There is no .Net Class that provides this functionality. We need to use the Windows Shell function (PathCompactPathEx) to do this.

PathCompactPathEx is a bool Shell Lightweight Utility Function that is available in the Windows shell. 

//Using
using System.Runtime.InteropServices;

//DLLImport -- Calling Native Function
[DllImport("shlwapi.dll", CharSet = CharSet.Auto, SetLastError = true)]

private static extern bool PathCompactPathEx(
System.Text.StringBuilder pszOut, string pszSrc, Int32 cchMax, 
Int32 dwFlags); 

//The text to Compact
string strLong = "C:\Program Files\EggHeadCafe\Publicati0ns\Today\Present.txt";

StringBuilder sbShort = new StringBuilder(260);
bool returnValue = PathCompactPathEx(sbShort , strLong , 20+1, 0);
//Shows Short Text with 20 Characters
txtShort.Text = sbShort .ToString();
Popularity  (518 Views)