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

ファイル名(ファイルパス)から拡張子を取得するコードを紹介します。

概要

拡張子を取得するには、System.IOの Pathクラスを使用します。
Path.GetExtension((ファイル名文字列));
で拡張子を取得できます。
GetExtension()メソッドは、"."を含む拡張子の文字列を返します。

使用例

string fullpath=@"C:\Windows\Web\Screen\img100.jpg";
string ext = System.IO.Path.GetExtension(fullPath); //extには".jpg"が代入されます。

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

実行結果

ext = ".jpg"

サンプルプログラム

UI

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

コード

下記のコードを記述します。
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;

namespace PathStringProcessing
{
  public partial class FormFilePath : Form
  {
    public FormFilePath()
    {
      InitializeComponent();
    }

    private void button_Reference_Click(object sender, EventArgs e)
    {
      if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
        textBox_Path.Text = openFileDialog1.FileName;
      }
      
    }

    private void button3_Click(object sender, EventArgs e)
    {
      string PathString = textBox_Path.Text;

      string fileExt = Path.GetExtension(PathString);
      textBox_Output.Text += fileExt + "\r\n";
    }
  }
}

解説

ファイル名のフルパスから拡張子を取得する場合は、System.IO.Path.GetExtension() メソッドを用います。

実行結果

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


上部のテキストにファイルのパスを入力します。


コードを実装したボタンをクリックします。(今回の場合は[拡張子取得]ボタンになります。)
クリックすると下部のテキストボックスにファイルの拡張子を表示します。


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