URLからファイルの拡張子を取得する - C#

URLからファイルの拡張子を取得するコードを紹介します。

概要

URLからファイルの拡張子を取得するためには、System.IOの Pathクラスを使用します。
Path.GetExtension((URL文字列));
で取得できます。

使用方法

string fullpath=@"http://www.ipentec.com/resource/banner.jpg";
string ext = System.IO.Path.GetExtension(fullPath); //extには".jpg"が代入されます。

writeln("ext = \"{0:s}\"",ext);

実行結果

ext = ".jpg"

サンプルプログラム

UI

下図のUIを作成します。ボタンを1つ、テキストボックスを2つ配置します。

コード

下記のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;

namespace PathStringProcessing
{
  public partial class FormUrlPath : Form
  {
    public FormUrlPath()
    {
      InitializeComponent();
    }
    
    private void button3_Click(object sender, EventArgs e)
    {
      string URLString = textBox_Path.Text;

      string fileName = Path.GetExtension(URLString);
      textBox_Output.Text += fileName + "\r\n";

    }
  }
}

解説

URLから、ファイルの拡張子を取得する場合は、System.IO.Path.GetExtension() メソッドを用いると取得できます。拡張子は GetExtension()メソッドの戻り値で取得できます。拡張子の文字列は"."を含みます。
(GetExtension()に"http://www.ipentec.com/sample.txt" を与えたのであれば、戻り値は".txt"となります。)

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


上部のテキストにURLを入力します。


Clickイベントにコードを記述したボタン(今回の場合は[拡張子取得]ボタン)をクリックします。入力されたURLのファイルの拡張子を取得し、下部のテキストボックスに表示します。テキストボックスのフォントがプロポーショナルフォントのため見づらいですが、"."がついた拡張子を表示しています。

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
掲載日: 2014-07-31
iPentec all rights reserverd.