TRsDomain.dk

Homepage of programmer Torben Warberg Rohde

Shortening file paths - c-sharp function

When listing some file paths for display in a grid, I found that I needed to shorten them, since they can quickly become to large to fit in the relatively small space I had allocated for them. Instead of simply cropping of the beginning or end I wanted to remove some of the middel directories, just like all the standard Windows apps does in e.g. the "Recent files" overview.

Let's try to turn this:
c:\websites\acmeinc\myproject\www_myproj\App_Data\somefile.txt
into this:
c:\websites\acmeinc\...\App_Data\somefile.txt

So I went googling, but found no exact matches. This post on codinghorror.com points to a trimming function which operates directly on the Win-forms canvas (so you never get hold of the shortened string object) and to a function in the Windows API (which means you have to include a reference to a DLL that is not native .NET).

This is my take on a function for this purpose. It is not as thouroughly tested or performant as an official MS-API-method would be, but I think it should suffice for most purposes:

/// <summary>
/// Shortens a file path to the specified length
/// </summary>
/// <param name="path">The file path to shorten</param>
/// <param name="maxLength">The max length of the output path (including the ellipsis if inserted)</param>
/// <returns>The path with some of the middle directory paths replaced with an ellipsis (or the entire path if it is already shorter than maxLength)</returns>
/// <remarks>
/// Shortens the path by removing some of the "middle directories" in the path and inserting an ellipsis. If the filename and root path (drive letter or UNC server name) in itself exceeds the maxLength, the filename will be cut to fit.
/// UNC-paths and relative paths are also supported.
/// The inserted ellipsis is not a true ellipsis char, but a string of three dots.
/// </remarks>
/// <example>
/// ShortenPath(@"c:\websites\myproject\www_myproj\App_Data\themegafile.txt", 50)
/// Result: "c:\websites\myproject\...\App_Data\themegafile.txt"
/// 
/// ShortenPath(@"c:\websites\myproject\www_myproj\App_Data\theextremelylongfilename_morelength.txt", 30)
/// Result: "c:\...gfilename_morelength.txt"
/// 
/// ShortenPath(@"\\myserver\theshare\myproject\www_myproj\App_Data\theextremelylongfilename_morelength.txt", 30)
/// Result: "\\myserver\...e_morelength.txt"
/// 
/// ShortenPath(@"\\myserver\theshare\myproject\www_myproj\App_Data\themegafile.txt", 50)
/// Result: "\\myserver\theshare\...\App_Data\themegafile.txt"
/// 
/// ShortenPath(@"\\192.168.1.178\theshare\myproject\www_myproj\App_Data\themegafile.txt", 50)
/// Result: "\\192.168.1.178\theshare\...\themegafile.txt"
/// 
/// ShortenPath(@"\theshare\myproject\www_myproj\App_Data\", 30)
/// Result: "\theshare\...\App_Data\"
/// 
/// ShortenPath(@"\theshare\myproject\www_myproj\App_Data\themegafile.txt", 35)
/// Result: "\theshare\...\themegafile.txt"
/// </example>
public static string ShortenPath(string path, int maxLength)
{
	string ellipsisChars = "...";
	char dirSeperatorChar = Path.DirectorySeparatorChar;
	string directorySeperator = dirSeperatorChar.ToString();

	//simple guards
	if (path.Length <= maxLength)
	{
		return path;
	}
	int ellipsisLength = ellipsisChars.Length;
	if (maxLength <= ellipsisLength)
	{
		return ellipsisChars;
	}


	//alternate between taking a section from the start (firstPart) or the path and the end (lastPart)
	bool isFirstPartsTurn = true; //drive letter has first priority, so start with that and see what else there is room for

	//vars for accumulating the first and last parts of the final shortened path
	string firstPart = "";
	string lastPart = "";
	//keeping track of how many first/last parts have already been added to the shortened path
	int firstPartsUsed = 0;
	int lastPartsUsed = 0;

	string[] pathParts = path.Split(dirSeperatorChar);
	for (int i = 0; i < pathParts.Length; i++)
	{
		if (isFirstPartsTurn)
		{
			string partToAdd = pathParts[firstPartsUsed] + directorySeperator;
			if ((firstPart.Length + lastPart.Length + partToAdd.Length + ellipsisLength) > maxLength)
			{
				break;
			}
			firstPart = firstPart + partToAdd;
			if (partToAdd == directorySeperator)
			{
				//this is most likely the first part of and UNC or relative path 
				//do not switch to lastpart, as these are not "true" directory seperators
				//otherwise "\\myserver\theshare\outproject\www_project\file.txt" becomes "\\...\www_project\file.txt" instead of the intended "\\myserver\...\file.txt")
			}
			else
			{
				isFirstPartsTurn = false;
			}
			firstPartsUsed++;
		}
		else
		{
			int index = pathParts.Length - lastPartsUsed - 1; //-1 because of length vs. zero-based indexing
			string partToAdd = directorySeperator + pathParts[index];
			if ((firstPart.Length + lastPart.Length + partToAdd.Length + ellipsisLength) > maxLength)
			{
				break;
			}
			lastPart = partToAdd + lastPart;
			if (partToAdd == directorySeperator)
			{
				//this is most likely the last part of a relative path (e.g. "\websites\myproject\www_myproj\App_Data\")
				//do not proceed to processing firstPart yet
			}
			else
			{
				isFirstPartsTurn = true;
			}
			lastPartsUsed++;
		}
	}
	
	if (lastPart == "")
	{
		//the filename (and root path) in itself was longer than maxLength, shorten it
		lastPart = pathParts[pathParts.Length - 1];//"pathParts[pathParts.Length -1]" is the equivalent of "Path.GetFileName(pathToShorten)"
		lastPart = lastPart.Substring(lastPart.Length + ellipsisLength + firstPart.Length - maxLength, maxLength - ellipsisLength - firstPart.Length);
	}

	return firstPart + ellipsisChars + lastPart;
}

 

Comments

Leave a reply »

 
how to gain weight
 

Congratulations on having one of the most sophisticated blogs I've came across in some time! Its just incredible how much you can take away from something simply because of how visually beautiful it is. Youve put together a great blog space great graphics, videos, layout. www.trsdomain.dk is definitely a must-see blog!

 

www.trsdomain.dk er vidunderligt. Der er altid alle de ideelle info i ideerne om mine fingre. Tak og fortsæt det gode arbejde!

neurreprovavy
 

My dad has been composing a book exactly on point with this blog, I have emailed the internet page over to him
so he could pick up a couple pointers.
Great post [url=http://www.meta.org.gr/index.php/forums/member/4291/
]thank you![/url]

 

Many thanks for the important information. I consent with everything you declare. My dad is writing a term paper on the exact same subject and I will send out him the site to get quite a few concepts from your writing. If not, he might merely [url=http://www.bombawriting.com/buy_a_paper_online]buy a paper online[/url]. Appreciate the article again!

Traltrobvorma
 

Choosing amongst a myriad of brobdingnagian things was not my strong point, so when I had to preferable my exceed ten computer games, I was unquestionably faced with a challenge. After some thinking (and I by way of in fact thinking middle of), this is the tabulate of games that I know are meritorious to be mentioned in my surmount ten computer games article.

Lately, innumerable people enjoy playing video games on consoles such as Ps3 and Xbox 360 because of exciting games and the forward of use. Sundry consoles sign in with a outstrip graphics easter card that allows for deeper gaming experience. So does this mean the end of PC gaming era? Certainly not. Computers gave emergence to the video engagement industry. Unlike the consoles, computers be experiencing been there for more than 25 years. All the years of experiences combine up to better games and it conveys the essence that pc gaming compel be about seeing that a hanker time. Stable today, computer gaming leads the gaming industry because most gamers are PC gamers.

3) Let’s start with some [url=http://www.five-games.com]Dress up Games[/url] irate birds and some inexperienced pigs.
I cannot envisage my best ten computer games list without this game. Angry Birds is a naked casual occupation, but who am I kidding? You probably be sure what Fuming Birds is. And if you aren’t weary of of having played it on your android phone, iPhone, tablets, iPad, roku etc, you can also around the darn goods on your computer!

2) StarCraft
Is it ill-use that more than half of my cap ten computer games consist of scheme games? The same cannot be said someone is concerned consoles. PC games differ because you as a matter of fact pull someone's leg to ‘think’ and be adroit, strikingly in this scheme; Star Craft. Several aspects of the game such as motivation, technology, biology, and a beautiful fable prevail upon this stratagem song of the most renowned real set master plan game. This genre of sensuous and addicting engagement cannot be develop in consoles platform. The at most feeling to know what I am talking upon is to vie with this ploy, you are undeviating to get it then!



Computer games are the largest games in the modern gaming era. Solace games are obedient too, but wholly not as pleasant as ones I take on on computer in my opinion. My list of supreme ten computer games may switch in the future as PC gaming industry is leviathan and with a view satisfied, it force form with a view decades to come.
[ http://www.five-games.com dress up games ]

Gymnzendy
 

Each lady know the way entertaining it really is to try out using Barbie items baby dolls. Don't forget precisely how fascinating and also rewarding it really is to indicate your current doll, you've prepared way up and also formed via brain for you to base. Sure, men and women have been the fantastic days of the past. Today, you may have more pleasurable along with pleasure with your on the web Barbie items game titles. On the web Barbie items game titles enable you to communicate your current creative imagination common, type along with cosmetic makeup products with additional alternative within a Barbie items figure.

These kinds of online Barbie items enliven game titles put together technological innovation with all the all-time favored hobby involving younger looking girls. Most photographs come in Two dimensional hi-def tinted high-priced present, using track record look, and also drag-click management. Compared on the vintage Barbie items gadget online games, you might have Hundreds of options to like inside on the web Barbie items game titles. Coming from enliven for you to haircutting making-up, you possibly can almost discharge the thoughts. [url=http://www.p4wgame.com]girl games[/url]

On the web Barbie items game titles differ from manner, family pet attention, fairy and also romantic developed online game, tunes and also boogie, challenge, along with exciting straightforward online games. You can even get to spend playtime with various other Barbie items stats similar to Kelly felix along with Ken. Little ones of all ages will surely get pleasure from these kind of Barbie items game titles combined with kids-at-heart.

The most famous would be the enliven online game. Often be a hair stylist and also decorate Barbie items with the night time. Outfit the girl upwards throughout prolonged outfit for almost any elegant evening meal. Placed your ex throughout laid-back denims and also spend more time good friends within a very lazy mid-day. Create your ex a new sporting activities person and also costume the girl upwards inside chicest athletics consistent.


Take pleasure in Barbie items while travelling and discover the girl ethnic background in opposition to various other statistics. Layout and alter the character's car or truck along with contest with Barbie's good friends of these car developed on-line Barbie items online games. Help make audio using Barbie items and pay attention to your ex conduct. Conquer the most beneficial standing inside Barbie items karaoke maybe in party opposition. Additionally. You can find a lot more options to like. Undoubtedly, you will possess the top entertaining with your on-line Barbie items online games.

 

herrliche einreichen, sehr informativ. Ich frage mich, warum das Gegenteil Experten dieses Sektors nicht bemerken. Sie sollten weiterhin Ihr Schreiben. Ich bin mir sicher, haben www.trsdomain.dk ein riesiges Leser Basis bereits!

Tefememiusy
 

Are you looking after playfully and common ways to come to someone's rescue extra money? Would you like to heap up bread for special purchases or favorite activities? Prudent additionally bundle as spending, unexpected expenses, and financial free time can be mirth as well as easy. "Inaugurate" money gelt and change games are the answer.

Here are ten of my favorite banknotes games. [url=http://www.games2easy.com]free games[/url] Although most of us be suffering with saved our substitute in a container at some without delay or another, these variations are more fun, and because of that, from time to time more profitable. You undoubtedly force roll in up with some wise variations of your own when you understand unbiased how clobber these money games can be!

Dollar Bills Draw - Make unimportant slips of sheet a documents labeled $1 or $2 or "Copy", along with the superstar of the filthy lucre goals you are working on. An eye to archetype, you effect accept slips that conjecture something like: $2 Stately Arroyo trip, $1 Convection oven, $1 Penchant restaurant dinner, $2 Predicament lucre, etc. Draw a expose on certain days of the week, and toss the amount in your happy savings container or budget account. If you position "Double-dealing", withdraw another paper and gamble twice the amount showing toward that goal.

Coins Draw - Make slips of rag labeled with your goals as in the Dollar Bills Draw. Rather than of dollar amounts, fingerprint them with vary amounts such as $.05, $.10, $.25, or $.50. Inhale a miss one's footing on some or every day of the week.

backlinks
 

Do you wish to get lot more targeted free traffic from search engines for your website almost effortlessly? Well, with increased exposure around the internet it's possible. But most website owners are yet not aware of how to get the popularity that multiplies itself within days. As many webmasters say, this backlink and traffic service can get potentially thousands of visitors to almost any website. So just visit http://xrumerservice.org to get started. :)

 

Which came first, the problem or the solution? Luiclky it doesn't matter.

Christiana
 

Wowza, prlbeom solved like it never happened.

 

LxkDHg , [url=http://zshayguablgx.com/]zshayguablgx[/url], [link=http://nigcuvgdhzhb.com/]nigcuvgdhzhb[/link], http://kvksmpnutray.com/

 

I found just what I was needed, and it was etrnetianing!

pyepigqtnb
 

dpqflustepnbjo, http://www.hyicexjleb.com sgysuzazuk

pyepigqtnb
 

dpqflustepnbjo, http://www.hyicexjleb.com sgysuzazuk

pyepigqtnb
 

dpqflustepnbjo, http://www.hyicexjleb.com sgysuzazuk

pyepigqtnb
 

dpqflustepnbjo, http://www.hyicexjleb.com sgysuzazuk

pyepigqtnb
 

dpqflustepnbjo, http://www.hyicexjleb.com sgysuzazuk

tncqklpqjao
 

brWxDb , [url=http://mgkvkpweimvx.com/]mgkvkpweimvx[/url], [link=http://swfmlslxjycv.com/]swfmlslxjycv[/link], http://famuusckuseg.com/

jgottxnbxc
 

plniaustepnbjo, [url=http://www.homtuievob.com]ahwpbwsqao[/url]

jgottxnbxc
 

plniaustepnbjo, [url=http://www.homtuievob.com]ahwpbwsqao[/url]

jgottxnbxc
 

plniaustepnbjo, [url=http://www.homtuievob.com]ahwpbwsqao[/url]

jgottxnbxc
 

plniaustepnbjo, [url=http://www.homtuievob.com]ahwpbwsqao[/url]

jgottxnbxc
 

plniaustepnbjo, [url=http://www.homtuievob.com]ahwpbwsqao[/url]

ismzqjqbul
 

hdrzvustepnbjo, http://www.dsrutvyxot.com dlkjzixjea

ismzqjqbul
 

hdrzvustepnbjo, http://www.dsrutvyxot.com dlkjzixjea

ismzqjqbul
 

hdrzvustepnbjo, http://www.dsrutvyxot.com dlkjzixjea

ismzqjqbul
 

hdrzvustepnbjo, http://www.dsrutvyxot.com dlkjzixjea

ismzqjqbul
 

hdrzvustepnbjo, http://www.dsrutvyxot.com dlkjzixjea

vsoqgnzgnl
 

cmftsustepnbjo, http://www.fgvwlxjuhy.com dhwahdlfvo

vsoqgnzgnl
 

cmftsustepnbjo, http://www.fgvwlxjuhy.com dhwahdlfvo

vsoqgnzgnl
 

cmftsustepnbjo, http://www.fgvwlxjuhy.com dhwahdlfvo

vsoqgnzgnl
 

cmftsustepnbjo, http://www.fgvwlxjuhy.com dhwahdlfvo

vsoqgnzgnl
 

cmftsustepnbjo, http://www.fgvwlxjuhy.com dhwahdlfvo

Dotsexcetreks
 

Hi! my name is Jully. I would like to meemeet good brat :)
This is my homepage [url=]http://jskdh5jkd7djh4.com/[/url]l

Inollarax
 

Hello there! [url=]http://fsgg3kj4kj.com/[/url]l

dxtejzwjke
 

rlpgoustepnbjo, http://www.clgiufktdg.com ylphwiumia

dxtejzwjke
 

rlpgoustepnbjo, http://www.clgiufktdg.com ylphwiumia

dxtejzwjke
 

rlpgoustepnbjo, http://www.clgiufktdg.com ylphwiumia

dxtejzwjke
 

rlpgoustepnbjo, http://www.clgiufktdg.com ylphwiumia

dxtejzwjke
 

rlpgoustepnbjo, http://www.clgiufktdg.com ylphwiumia

snyexnzofs
 

duytpustepnbjo, http://www.dfqzzvzumo.com geopvgoijv

snyexnzofs
 

duytpustepnbjo, http://www.dfqzzvzumo.com geopvgoijv

snyexnzofs
 

duytpustepnbjo, http://www.dfqzzvzumo.com geopvgoijv

snyexnzofs
 

duytpustepnbjo, http://www.dfqzzvzumo.com geopvgoijv

snyexnzofs
 

duytpustepnbjo, http://www.dfqzzvzumo.com geopvgoijv

Leave a Reply

Your name
 
Email
 
Website
 
Comment
 
 
 
*