Mass Rename of Files

digitall

New member
Joined
Jan 29, 2008
Messages
2
Programming Experience
3-5
I am trying to write a simple console app that will traverse all directories in a "parent" directory (presumably an argument passed when the application is run from the command prompt) that will rename all files ending with a certain extention (.sln) to "[filename] dev.sln". I've tried searching around for a way to traverse directories recursively but am not finding any good examples outside of "here is how to list the files in a directory." Can anyone point me in the right direction? The actual rename part is easy, but traversing the directories doesn't seem to be as straight-forward.
 
Use a recursive sub:
VB.NET:
    Private Sub GetFiles(ByVal SourceDir As String)
        Try
            For Each Element As String In Directory.GetFileSystemEntries(SourceDir)
                If Directory.Exists(Element) = True Then
                    'Is a folder
                    Call GetFiles(Element)
                Else
                    'Is a file
                    
                End If
            Next Element
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error found", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
 
I also forgot to tell you to add 'Imports System.IO' to the top of the class/module that this sub will be in
 
FileSystemInfo performs better (around 35% in my measures)
VB.NET:
Private Sub GetFiles(ByVal SourceDir As IO.DirectoryInfo)
    Try

        For Each Element As IO.FileSystemInfo In SourceDir.GetFileSystemInfos
            If TypeOf Element Is IO.DirectoryInfo Then
                'Is a folder
                Call GetFiles2(Element)
            Else
                'Is a file

            End If
        Next Element
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error found", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub
So for SourceDir instead of "folder string" give first parameter as New IO.DirectoryInfo("folder string")

I would normally use IO.Path.ChangeExtension method to do the extension change, but seems it doesn't work with "double" extensions like that... err.
 
Faster again if looking for particular files is to do one lookup for directories and one for files:
VB.NET:
Private Sub GetFiles(ByVal SourceDir As String)
    Try
        For Each dir As String In IO.Directory.GetDirectories(SourceDir)
            GetFiles3(dir)
        Next
        For Each file As String In IO.Directory.GetFiles(SourceDir, "*.sln")

        Next
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error found", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub
Doing lots of test with this I didn't get much difference between string paths and DirectoryInfo/FileInfo, but FileInfo simplifies some code sometimes.
 
Back
Top