ファイルパスからファイル名を取得するコードを紹介します。
ファイルパスの文字列からドライブ名や上位のディレクトリのパスを取り除いたファイル名の文字列のみを取得したい場合があります。
この記事では、ファイルパスの文字列からファイル名部分の文字列を取得するコードを紹介します。
PathクラスのGetFileName()
メソッドを用いてファイルパスからファイル名を取得します。
下図のフォームを作成します。テキストボックスを2つ、ボタンを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;
namespace GetFileName
{
public partial class FormGetFileName : Form
{
public FormGetFileName()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string FilePath = textBox1.Text;
string FileName = Path.GetFileName(FilePath);
textBox2.Text = FileName;
}
private void button2_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
textBox1.Text = openFileDialog1.FileName;
}
}
}
}
上部のテキストボックスに入力された文字列を FilePath
変数に代入します。
string FilePath = textBox1.Text;
Path.GetFileName()
メソッドを呼び出し、FilePath
変数に代入されている文字列からファイル部分のみを取得し、FileName
変数に代入します。
string FileName = Path.GetFileName(FilePath);
FileName
変数の値を株のテキストボックスに表示します。
textBox2.Text = FileName;
button2はボタンがクリックされた際にダイアログボックスを開き選択したファイルのファイルパスを上部のテキストボックスに表示する動作です。
private void button2_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
textBox1.Text = openFileDialog1.FileName;
}
}
プロジェクトを実行します。下図のウィンドウが表示されます。
上部のテキストボックスにファイルパスを入力します。今回はD:\Storage\data\price.txt
を入力します。
入力後[button1]ボタンをクリックします。下部のテキストボックスにファイル名の文字列price.txt
が表示されます。
他のパス文字列の動作も確認します。C:\Windows\Web\Wallpaper\Windows\img19.jpg
を入力し[button1]をクリックした結果が下図です。
ファイル名部分のimg19.jpg
の文字列が下部のテキストボックスに表示されます。