2012-05-10 17 views
5

URLのサブディレクトリの名前を抽出し、ASP.NET C#のサーバー側の文字列に保存したいと考えています。たとえば、次のようなURLがあるとします:ASP.NETのURLからサブディレクトリ名を抽出するC#

http://www.example.com/directory1/directory2/default.aspx 

URLから「directory2」という値を取得するにはどうすればよいですか?

+1

あなたは、もう少し正確にしたいことがあります。あなたは、ページの前に、最後のサブディレクトリをしたいですか?つまり、URLが 'http:// www.abc.com/foo/bar/baz/default.aspx'だった場合、' baz'が必要でしょうか? – Filburt

+0

最新の回答をご覧ください。 – jams

答えて

12

ウリクラスはsegmentsというプロパティを持っています

var uri = new Uri("http://www.example.com/directory1/directory2/default.aspx"); 
Request.Url.Segments[2]; //Index of directory2 
+0

あなたはそれに私を打つ。 :) –

+0

Uriのような便利なものがあるときは、文字列の分割/解析を避けるために最高です。 OPは彼がいつも最後のサブディレクトリを望んでいるかどうかは指定していませんでした。おそらくあなたはこのケースの代替案を投げることができます。 – Filburt

+0

ありがとう!これは完全に機能しました! – Kevin

0

あなたはここでページディレクトリ

string words = "http://www.example.com/directory1/directory2/default.aspx"; 
string[] split = words.Split(new Char[] { '/'}); 
string myDir=split[split.Length-2]; // Result will be directory2 

を選択したい場合は、これを試してみてください/

にそれを分割するstringクラスのsplitメソッドを使用することができますが、MSDNからの例です。 splitメソッドの使い方

using System; 
public class SplitTest 
{ 
    public static void Main() 
    { 
    string words = "This is a list of words, with: a bit of punctuation" + 
          "\tand a tab character."; 
    string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' }); 
    foreach (string s in split) 
    { 
     if (s.Trim() != "") 
      Console.WriteLine(s); 
    } 
    } 
} 
// The example displays the following output to the console: 
//  This 
//  is 
//  a 
//  list 
//  of 
//  words 
//  with 
//  a 
//  bit 
//  of 
//  punctuation 
//  and 
//  a 
//  tab 
//  character 
1

私は.LastIndexOfを使用します( "/")、そこから逆方向に働くと思います。

1

System.Uriを使用すると、パスのセグメントを抽出できます。例:[ "/"、 "directory1の/"、 "directory2 /"、「デフォルト:

public partial class WebForm1 : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     var uri = new System.Uri("http://www.example.com/directory1/directory2/default.aspx"); 
    } 
} 

、プロパティ "uri.Segments" は、このような4つのセグメントを含む文字列(文字列[])であります.aspx "]。

1

これはsortherコードです:

string url = (new Uri(Request.Url,".")).OriginalString 
関連する問題