ASP.NET/C#: Get second directory in URL path

Using ASP.NET, how can I get the value of the second directory in a URL?

For example,
http://example.com/xyz/hello/123/555.jpg
The value of the string xyz should be "hello".

http://example.com/123/world/abc/123.jpg
The value of the string xyz should be "world".
LVL 16
hankknightAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ArgentiCommented:
1. call the Request.Url.AbsoluteUri to get your current script URL path,
2. remove "http://" prefix
3. Split on "/" to get an array of strings
4. pull your second value out of the array (after testing if it exists)
0
AshokCommented:
public int GetNthIndex(string s, char t, int n)
{
    int count = 0;
    for (int i = 0; i < s.Length; i++)
    {
        if (s[i] == t)
        {
            count++;
            if (count == n)
            {
                return i;
            }
        }
    }
    return -1;
}

int i1 = GetNthIndex(URL, '/', 2);
ini i2 = GetNthIndex(URL, '/', 3);
string input = @"http://example.com/xyz/hello/123/555.jpg";
string sub = input.Substring(i1+1, i2+1);

Open in new window

0
hankknightAuthor Commented:
Thank you both, but are 21 lines of code really required for this?  Any way to do this in 1 or 2 steps with 1 or 2 lines?
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

ArgentiCommented:
or

string path = HttpContext.Current.Request.Url.AbsolutePath;

Open in new window

then
string[] dirs = path.Split('/');

Open in new window

and check for your n-th desired element

http://stackoverflow.com/questions/593709/how-to-get-the-url-of-the-current-page-in-c-sharp
0
AshokCommented:
string sub = input.Substring(i1+1, i2);

I do not have C# Visual Studio so I can not test.

Please adjust i2 accordingly.  Like i2-1 or i2.

Thanks,
Ashok
0
ArgentiCommented:
or you can use the String.Split( ) method

http://msdn.microsoft.com/en-us/library/vstudio/b873y76a.aspx
0
Vikram Singh SainiSoftware Engineer cum AD DeveloperCommented:
// Get directory hello from this url
const string url = "http://example.com/xyz/hello/123/555.jpg";

var uri = new Uri(url);

// The below line will give output: hello
// And will also work for second url too
Console.WriteLine("URI Segments: " + uri.Segments[2].Replace(@"/", ""));

Open in new window

0
AshokCommented:
21 lines of code is not that much.  Code runs extremely fast.
0
ArgentiCommented:
Sample code:

        static void Main(string[] args)
        {
            string path = "/xyz/hello/123/555.jpg"; // <- you get this by calling HttpContext.Current.Request.Url.AbsolutePath in your ASP.NET code;
            string[] dirs = path.Split(new char[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
            Console.WriteLine(dirs[0]); // <- outputs xyz
        }

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
AshokCommented:
public int GetNthIndex(string s, char t, int n) {
    int count = 0;
    for (int i = 0; i < s.Length; i++) {
        if (s[i] == t) {
            count++;
            if (count == n) 
                return i;
        }
    }
    return -1;
}
int i1 = GetNthIndex(URL, '/', 2);
ini i2 = GetNthIndex(URL, '/', 3);
string input = @"http://example.com/xyz/hello/123/555.jpg";
string sub = input.Substring(i1+1, i2);

Open in new window

0
AshokCommented:
21 lines are reduced to 15 lines.
0
AshokCommented:
public int GetNthIndex(string s, char t, int n) {
    int count = 0;
    for (int i = 0; i < s.Length; i++) {
        if (s[i] == t) {
            count++;
            if (count == n) 
                return i;
        }
    }
    return -1;
}
string URL = @"http://example.com/xyz/hello/123/555.jpg";
int i1 = GetNthIndex(URL, '/', 2);
int i2 = GetNthIndex(URL, '/', 3);
string sub = URL.Substring(i1+1, i2);

Open in new window

0
käµfm³d 👽Commented:
Using regex:

string secondDir = System.Text.RegularExpressions.Regex.Match(url, "(?<=(?<!/)/[^/]+/)[^/]+").Value;

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.