How to Get the Name of the Current Folder from the URL

The Situation:

You need to get the name of the current page request folder from the URL.

A Solution:

Use this method:

public string GetCurrentFolderName()
{
	//get current file path 
	string folder = System.Web.HttpContext.Current.Request.FilePath;

	//find the position of the last '/' 
	int intPos = folder.LastIndexOf("/");

	// if it is not the root folder...
	if ( intPos > 0 )
	{
		//cut off all characters after the last '/' 
		folder = folder.Substring(1, intPos - 1);

		//find the position of the last '/' in the new string 
		int intPos2 = folder.LastIndexOf("/");

		//get the length of the characters between the two '/' 
		int intLength = ( intPos - 1 ) - ( intPos2 + 1 );

		//get the characters between the 2 '/' 
		folder = folder.Substring(intPos2 + 1, intLength);
	}
	else
	{
		folder = "";
	}

	return folder;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s