URLのサブディレクトリの名前を抽出し、ASP.NET C#のサーバー側の文字列に保存したいと考えています。たとえば、次のようなURLがあるとします:ASP.NETのURLからサブディレクトリ名を抽出するC#
http://www.example.com/directory1/directory2/default.aspx
URLから「directory2」という値を取得するにはどうすればよいですか?
URLのサブディレクトリの名前を抽出し、ASP.NET C#のサーバー側の文字列に保存したいと考えています。たとえば、次のようなURLがあるとします:ASP.NETのURLからサブディレクトリ名を抽出するC#
http://www.example.com/directory1/directory2/default.aspx
URLから「directory2」という値を取得するにはどうすればよいですか?
ウリクラスはsegmentsというプロパティを持っています
var uri = new Uri("http://www.example.com/directory1/directory2/default.aspx");
Request.Url.Segments[2]; //Index of directory2
あなたはここでページディレクトリ
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
私は.LastIndexOfを使用します( "/")、そこから逆方向に働くと思います。
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 "]。
これはsortherコードです:
string url = (new Uri(Request.Url,".")).OriginalString
あなたは、もう少し正確にしたいことがあります。あなたは、ページの前に、最後のサブディレクトリをしたいですか?つまり、URLが 'http:// www.abc.com/foo/bar/baz/default.aspx'だった場合、' baz'が必要でしょうか? – Filburt
最新の回答をご覧ください。 – jams