Introduction
This article deals with how it is possible to manage the renaming of several files at the same time using VB.NET. Multiple files can be renamed using search by extension, file name, search string, etc. Obviously, there is the problem of how to select all the files or some files, this problem is solved with a listview
.
Using the Code
Essential routine! The problem is that when you extract text from the listview
, it needs to be cleaned of the added words "listview: {" (actually 16 chars) and "}
" placed at the end of the text.
If allfiles = True Then
For Each file In ListView1.Items
files = file.ToString
Dim lenn As Integer = files.Length
files = Mid(Replace(files, "}", ""), 16, lenn)
filepath_new = Replace(files, ComboBox1.SelectedItem, TextBox1.Text)
Try
My.Computer.FileSystem.RenameFile_
(files, IO.Path.GetFileName(filepath_new))
Catch ex As Exception
RichTextBox1.Text &= ex.Message & vbCrLf
End Try
Next
ListView1.Items.Clear()
ElseIf allfiles = False Then
For Each file In ListView1.SelectedItems
files = file.ToString
Dim lenn As Integer = files.Length
files = Mid(Replace(files, "}", ""), 16, lenn)
filepath_new = Replace(files, ComboBox1.SelectedItem, TextBox1.Text)
Try
My.Computer.FileSystem.RenameFile_
(files, IO.Path.GetFileName(filepath_new))
Catch ex As Exception
RichTextBox1.Text &= ex.Message & vbCrLf
End Try
Next
For Each i As ListViewItem In ListView1.SelectedItems
ListView1.Items.Remove(i)
Next
End If
Basic Principles
In a very simple way:
- Extract the selected items from the
listview
- Clean text and remove curly braces
- Find selected text or extension
- Replace text or extension
- Rename the file from VB
Step by Step Analysis
It is interesting to know that the richtextbox
seems to be much faster than the listview
. The program could handle the renaming also from the richtextbox
, but it would lose the multiple selection of the listview
.
The code has been tested with 2000 files.
Conclusion and Points of Interest
You always need to be careful with multiple renaming. The code has been designed for use of small quantities of files. For large numbers, it is perhaps better to use the tools of the operating system in the command line.
History
- 1st December, 2022: Initial version