火曜日, 9月 30, 2025

Visual Studio Basic_43 
同一階層内のファイル名入れ替え

同一階層内のファイル名を入れ替える処理をすることが多いので、安全を考えてプログラムしてみました。なお、同種類のファイルに限定していますが、そのうち別階層対応版を考えてみます。

レイアウトは上の様にしました。
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 = Label1.Text
Dim fileB = 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

' A と B が同じフォルダ内か確認
Dim dirA = Path.GetDirectoryName(fileA)
Dim dirB = Path.GetDirectoryName(fileB)
If dirA <> dirB Then
MessageBox.Show _
            ("同じフォルダ内のファイルである必要があります。")
Exit Sub
End If

Try
Dim tempFile = Path.Combine(dirA, "TempFile.tmp")

' A → Temp
File.Move(fileA, tempFile)
' B → A
File.Move(fileB, fileA)
' Temp → B
File.Move(tempFile, fileB)

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

Private Sub Button4_Click(sender As Object, _
        e As EventArgs) Handles Button4.Click
Label1.ResetText()
Label2.ResetText()
End Sub

Private Sub Button5_Click(sender As Object, _
        e As EventArgs) Handles Button5.Click
End
End Sub
End Class
------------------

起動直後の画面。
用意した2つのファイルの名称を変更します。

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

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

ファイル名は入れ替わります。