Search code examples
vb.netsortingfile-rename

Renaming multiple files by name


I'm writing a little program that is supposed to rename multiple files in a chosen directory by the filenames. this is what I use now:

    Dim sourcePath As String = dir
    Dim searchPattern As String = "*." & ComboBox3.Text
    Dim i As Integer = 1
    For Each fileName As String In Directory.GetFiles(sourcePath, searchPattern, SearchOption.AllDirectories)
        File.Move(Path.Combine(sourcePath, fileName), Path.Combine(sourcePath, type & i & "." & ComboBox3.Text))
        i += 1
    Next

But i want it to be more like:

    For Each fi As FileInfo In Directory.GetFiles(searchPattern).OrderBy(Function(s) s.FullName)
        File.Move(Path.Combine(sourcePath, fileName), Path.Combine(sourcePath, type & i & "." & ComboBox3.Text))
        i += 1
    Next

This is how far I've gotten, but it's not working as i hoped. Also, I was wondering if it is possible to exclude file-types with the GetFiles, i don't want it to rename text-files.

Thanks :)

Edit: The first code works almost perfect, it takes the dir from a 'FolderBrowserDialog' and renames all the files within the path-folder. The problem is that it sometimes get the order wrong: lets say i got these 3 files:

01Movie.avi, 07Movie.avi and 11Movie.avi

I want them to be renamed in the order they are in the folder by name:

01Movie.avi should be Movie1.avi, 07Movie.avi -> Movie2.avi and 11Movie.avi -> Movie3.avi


Solution

  • Try not to modify a collection you are still looping through. Created a detatched array to work with. Then sort your new array to get them in the order you described.

    Keep in mind that you have SearchOption.AllDirectories, this is going to return subs, so your filename array may not be what you were thinking... Either change the logic of the sort or handle subs separately.

    'detached array of file names
     Dim fileNames() As String = Directory.GetFiles(sourcePath, searchPattern)
    
     'sort the names  System.Array.Sort(Of String)(fileNames)
     Dim newFileName As String  
     For Each fileName As String In fileNames
    
       'manipulate you filename here    
       'Path.GetFileNameWithoutExtension(fileName) might help   
       'Path.GetExtension(fileName) might help
    
        newFileName =  "newFileNameWithoutExtension" & i.ToString
    
        File.Move(Path.Combine(Path.GetDirectoryName(fileName), fileName), Path.Combine(Path.GetDirectoryName(fileName), newFileName))
         i += 1  
     Next