Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to shrink file path to be more human readable

Tags:

c#

.net

filepath

Is there any function in c# to shink a file path ?

Input: "c:\users\Windows\Downloaded Program Files\Folder\Inside\example\file.txt"

Output: "c:\users\...\example\file.txt"

like image 249
André Pontes Avatar asked Dec 02 '11 17:12

André Pontes


2 Answers

Nasreddine answer was nearly correct. Just specify StringBuilder size, in your case:

[DllImport("shlwapi.dll", CharSet = CharSet.Auto)]
static extern bool PathCompactPathEx(
                       [Out] StringBuilder pszOut, 
                       string szPath, 
                       int cchMax, 
                       int dwFlags);

static string PathShortener(string path, int length)
{
    StringBuilder sb = new StringBuilder(length + 1);
    PathCompactPathEx(sb, path, length, 0);
    return sb.ToString();
}
like image 172
Daniele Avatar answered Oct 06 '22 00:10

Daniele


Jeff Atwood posted a solution to this on his blog and here it is :

[DllImport("shlwapi.dll", CharSet = CharSet.Auto)]
static extern bool PathCompactPathEx([Out] StringBuilder pszOut, string szPath, int cchMax, int dwFlags);

static string PathShortener(string path, int length)
{
    StringBuilder sb = new StringBuilder();
    PathCompactPathEx(sb, path, length, 0);
    return sb.ToString();
}

It uses the unmanaged function PathCompactPathEx to achieve what you want.

like image 21
Nasreddine Avatar answered Oct 06 '22 00:10

Nasreddine