Search code examples
vb.netfile-rename

Renaming ending of all files in a folder and subfolder (*.log to *.txt)


Is it possible to rename all the files in a folder and subfolder with a simple program, using vb.NET I'm quite green and not sure if this is even possible.

D:\Main\ <--- there are 10 Files. D:\Main\Sub\ <--- there are some more files ...

The files has always the ending "log" like "this is a test.log" or "this_is_the_second.log". All the files-ending rename to "txt" like "this is a test.txt" or "this_is_the_second.txt".

I tried allready this code, but it doesn´t work :

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    renameFilesInFolder()
End Sub
Private Sub renameFilesInFolder()
    Dim sourcePath As String = "D:\Main"
    Dim searchPattern As String = "*.log"
    For Each fileName As String In Directory.GetFiles(sourcePath, searchPattern, SearchOption.AllDirectories)
        File.Move(Path.Combine(sourcePath, fileName), Path.Combine(sourcePath, ".txt"))

    Next
End Sub

Please help me!?!?!


Solution

  • Private Sub RenameFilesInFolder()
        Dim sourcePath As String = "D:\Main"
        Dim searchPattern As String = "*.log"
    
        For Each currentFilePath As String In Directory.GetFiles(sourcePath, searchPattern, SearchOption.AllDirectories)
            Dim newFilePath = Path.ChangeExtension(currentFilePath, ".txt")
    
            File.Move(currentFilePath, newFilePath)
        Next
    End Sub
    

    The GetFiles method gets the full file path, not just the name. Path.Combine(sourcePath, fileName) would result in values like "D:\MainD:\Main\Sub\test.log" while Path.Combine(sourcePath, ".txt") would have resulted in the value "D:\Main.txt" every time.