URLからファイル名を取得する

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

概要

URLから、URLが示すファイル名を取得したい場合があります。具体的な例として、http://www.ipentec.com/res/icon.png であれば icon.png の文字列を取得する場合があります。
URLからファイル名を取得する場合は、PathクラスのGetFileName() メソッドを用います。

プログラム

UI

以下のUIを作成します。(ボタンは1つしか利用しません)
URLからファイル名を取得する:画像1

コード

下記のコードを記述します。
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 button2_Click(object sender, EventArgs e)
    {
      string URLString = textBox_Path.Text;

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

    }
  }
}

解説

URLからファイル名を取得する場合は System.IO.Path.GetFileName() メソッドを呼び出して取得できます。

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。
URLからファイル名を取得する:画像2

URLを上部のテキストボックスに入力します。
URLからファイル名を取得する:画像3

コードを実装したボタン(今回は[ファイル名取得]ボタン)をクリックします。入力されたURLから、ファイル名を取得しテキストボックスに表示します。
URLからファイル名を取得する:画像4

拡張子を含まないファイル名を取得する場合

拡張子を除いたファイル名を取得する場合です。

UI

下図のUIを作成します。
URLからファイル名を取得する:画像5

コード

下記のコードを記述します。
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 button4_Click(object sender, EventArgs e)
    {
      string URLString = textBox_Path.Text;

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

    }
  }
}

解説

URLから拡張子を除いたファイル名を取得する場合は System.IO.Path.GetFileNameWithoutExtension() メソッドを呼び出して取得できます。

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。
URLからファイル名を取得する:画像6

URLを上部のテキストボックスに入力します。
URLからファイル名を取得する:画像7

コードを実装したボタン(今回は[ファイル名取得]ボタン)をクリックします。入力されたURLから、拡張子を含まないファイル名を取得しテキストボックスに表示します。
URLからファイル名を取得する:画像8

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