I searched online for a way to shorten a path in .NET. I couldn’t find a solid solution so I had to roll my own. The following method will handle your basic compression needs. It has also been smartened-up to perform some base filename care to reveal the most import characters first. It can handle both
Windows
and Mac
file system structures. It can also properly compact network paths.The method can also take a custom delimiter of one or more characters. A custom delimiter is nice in cases where an actual ellipsis (the default character) won’t render properly in the UI. Here is what you can expect:
Win | Mac | Network |
---|---|---|
…s… |
…s… |
…s… |
…stripes… |
…stripes… |
…stripes… |
…stripes.jpg |
…stripes.jpg |
…stripes.jpg |
…\stripes.jpg |
…/stripes.jpg |
…\stripes.jpg |
C…\stripes.jpg |
/…/stripes.jpg |
\…\stripes.jpg |
C:…\stripes.jpg |
/U…/stripes.jpg |
\\…\stripes.jpg |
C:\Users\chadk\…\stripes.jpg |
/Users/chadk/Pi…/stripes.jpg |
\\ps1\Themes\Mi…\stripes.jpg |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
/// <summary> /// /// </summary> /// <param name="absolutepath">The path to compress</param> /// <param name="limit">The maximum length</param> /// <param name="delimiter">The character(s) to use to imply incompleteness</param> /// <returns></returns> public string ShrinkPath(string absolutepath, int limit, string delimiter = "…") { //no path provided if (string.IsNullOrEmpty(absolutepath)) { return ""; } var name = Path.GetFileName(absolutepath); int namelen = name.Length; int pathlen = absolutepath.Length; var dir = absolutepath.Substring(0, pathlen - namelen); int delimlen = delimiter.Length; int idealminlen = namelen + delimlen; var slash = (absolutepath.IndexOf("/") > -1 ? "/" : "\\"); //less than the minimum amt if (limit < ((2 * delimlen) + 1)) { return ""; } //fullpath if (limit >= pathlen) { return absolutepath; } //file name condensing if (limit < idealminlen) { return delimiter + name.Substring(0, (limit - (2 * delimlen))) + delimiter; } //whole name only, no folder structure shown if (limit == idealminlen) { return delimiter + name; } return dir.Substring(0, (limit - (idealminlen + 1))) + delimiter + slash + name; } |