目次

相対パスや相対URIを取得する - C#

C#で相対パスや相対URIを取得するコードを紹介します。

概要

相対URIや相対パスを取得する場合には Uriクラスと MakeRelativeメソッドを利用します。

コード例

以下のコードはhttp://news.ipentec.comに対する"http://news.ipentec.com/pub/data/"の相対URIを求めます。
protected void Page_Load(object sender, EventArgs e)
{
  Uri uri1 = new Uri("http://news.ipentec.com");
  Uri uri2 = new Uri("http://news.ipentec.com/pub/data/");

  Label1.Text = uri1.MakeRelative(uri2);
}
結果は
pub/data/
がラベルに表示されます。

またuri1のURLの末尾に/を含めた場合の下記コード
protected void Page_Load(object sender, EventArgs e)
{
  Uri uri1 = new Uri("http://news.ipentec.com/");
  Uri uri2 = new Uri("http://news.ipentec.com/pub/data/");

  Label1.Text = uri1.MakeRelative(uri2);
}
この場合にも、
pub/data/
がラベルに表示されます。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2010-01-28
iPentec all rights reserverd.