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

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

概要

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

プログラム

UI

以下のUIを作成します。(ボタンは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を上部のテキストボックスに入力します。


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

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

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

UI

下図のUIを作成します。

コード

下記のコードを記述します。
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を上部のテキストボックスに入力します。


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


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