Imports System.IO
Public Class frmRenomearArquivos
Private Sub btnbuscarPasta_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnDefinirDiretório.Click
If Me.dirCaminho.ShowDialog() = Windows.Forms.DialogResult.OK Then
Me.txtCaminho.Text = Me.dirCaminho.SelectedPath
Me.BuscarArquivos(Me.txtCaminho.Text)
End If
End Sub
Private Sub btnRenomear_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnRenomear.Click
If String.IsNullOrEmpty(Me.txtCaminho.Text) Then
MessageBox.Show("Defina o diretório!", "Atanção!", _
MessageBoxButtons.OK, MessageBoxIcon.Stop)
Me.btnDefinirDiretório.Focus()
Exit Sub
End If
If String.IsNullOrEmpty(Me.txtLocalizar.Text) Or _
String.IsNullOrEmpty(Me.txtSubstituir.Text) Then
MessageBox.Show("Preencher campos obrigatórios!", "Atenção!", _
MessageBoxButtons.OK, MessageBoxIcon.Stop)
Me.txtLocalizar.Focus()
Exit Sub
End If
Try
Me.RenomearArquivos()
Me.BuscarArquivos(Me.txtCaminho.Text)
Me.txtLocalizar.Clear()
Me.txtSubstituir.Clear()
Me.txtLocalizar.Focus()
Catch ex As Exception
MessageBox.Show(ex.Message, "Erro!", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub txtLocalizar_GotFocus(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles txtLocalizar.GotFocus
Me.txtLocalizar.SelectAll()
End Sub
Private Sub txtSubstituir_GotFocus(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles txtSubstituir.GotFocus
Me.txtSubstituir.SelectAll()
End Sub
''' <summary>
''' Renomeia os arquivos
''' </summary>
Private Sub RenomearArquivos()
For Each Arquivo As String In Directory.GetFiles(Me.txtCaminho.Text)
Dim NovoNome As String = String.Empty
Dim NomeArquivo As String = String.Empty
' Extrai o diretório do nome do arquivo
If Arquivo.IndexOf("\") >= 0 Then
NomeArquivo = Arquivo.Substring(0, Arquivo.LastIndexOf("\"))
Else
NomeArquivo = System.Environment.CurrentDirectory
End If
' Define o novo nome para o arquivo
NovoNome = Replace(Arquivo.Substring(Arquivo.LastIndexOf("\") + 1), _
Me.txtLocalizar.Text, Me.txtSubstituir.Text)
' Renomeia o arquivo
System.IO.File.Move(Arquivo, NomeArquivo & "\" & NovoNome)
MessageBox.Show("Os arquivos foram renomeados corretamente!", "Confirmação", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
Next
End Sub
''' <summary>
''' Preenche o ListBox com o nome dos arquivos
''' que estiverem no diretório selecionado
''' </summary>
''' <param name="pDiretorio">Diretório dos arquivos a serem renomeados</param>
Private Sub BuscarArquivos(ByVal pDiretorio As String)
Me.lsbArquivos.Items.Clear()
If Directory.Exists(pDiretorio) Then
For Each Arquivo As String In Directory.GetFiles(pDiretorio)
Me.lsbArquivos.Items.Add(Arquivo.Substring(Arquivo.LastIndexOf("\") + 1))
Next
Else
MessageBox.Show("Diretório inexistente!" & vbCrLf & pDiretorio, "Erro!", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
End Class