水曜日, 10月 15, 2025

Visual Studio Basic_44 
同一階層内のファイル名入れ替え Vol.2

今回同一階層内のファイルに限定していますが、拡張子は変更されません。

レイアウトは上の様にしました。
L=Label
B=Button

ソースの「-----------------」は区切り線なので記述の必要はありません。

青字は自動入力部分で修正の必要はありません。 黒字が入力部分です。 緑字はコメント文なので記述の必要はありません。

------------------
Public Class Form1
' Button1: ファイルAを選択してLabel1に表示
Private Sub Button1_Click(sender As Object, _
        e As EventArgs) Handles Button1.Click
Using ofd As New OpenFileDialog
ofd.Title = "ファイルAを選択してください"
If ofd.ShowDialog() = DialogResult.OK Then
Label1.Text = ofd.FileName
End If
End Using
End Sub

' Button2: ファイルBを選択してLabel2に表示
Private Sub Button2_Click(sender As Object, _
        e As EventArgs) Handles Button2.Click
Using ofd As New OpenFileDialog
ofd.Title = "ファイルBを選択してください"
If ofd.ShowDialog() = DialogResult.OK Then
Label2.Text = ofd.FileName
End If
End Using
End Sub

' Button3: ファイル名だけを入れ替える(拡張子はそのまま)
Private Sub Button3_Click(sender As Object, _
        e As EventArgs) Handles Button3.Click
Dim fileA As String = Label1.Text
Dim fileB As String = Label2.Text

If String.IsNullOrWhiteSpace(fileA) _
            OrElse String.IsNullOrWhiteSpace(fileB) Then
MessageBox.Show("両方のファイルを指定してください。")
Exit Sub
End If
If Not File.Exists(fileA) OrElse Not File.Exists(fileB) Then
MessageBox.Show("指定されたファイルが存在しません。")
Exit Sub
End If

Dim dirA As String = Path.GetDirectoryName(fileA)
Dim dirB As String = Path.GetDirectoryName(fileB)

' 同じフォルダにあることが前提
If dirA <> dirB Then
MessageBox.Show _
            ("同じフォルダ内のファイルを選択してください。")
Exit Sub
End If

Try
Dim nameA As String = _
                Path.GetFileNameWithoutExtension(fileA)
Dim nameB As String = _
                Path.GetFileNameWithoutExtension(fileB)
Dim extA As String = Path.GetExtension(fileA)
Dim extB As String = Path.GetExtension(fileB)

Dim tempFile As String = _
                Path.Combine(dirA, "TempFile" & extA)

' A → Temp
File.Move(fileA, tempFile)
' B → A (Bの拡張子のまま)
File.Move(fileB, Path.Combine(dirA, nameA & extB))
' Temp → B (Aの拡張子のまま)
File.Move(tempFile, Path.Combine(dirA, nameB & extA))

MessageBox.Show("ファイル名を入れ替えました。")
Catch ex As Exception
MessageBox.Show("エラー: " & ex.Message)
End Try
End Sub
End Class
------------------

起動直後の画面。


用意した2つのファイルの名称を変更します。

[File A]と[File B]をクリックしてファイルを指定して[ファイル名入れ替え]をクリックして問題がなければ・・・

上のアラートが表示され・・・

拡張子はそのままでファイル名は入れ替わります。