Replace Character in the File Name RRS feed

  • Question

  • User-768405968 posted

    Basically I'm kind of new to VB, can someone please help me make a program that:

    goes through every file in a directory and replaces any “$” characters in the filename with “_”.

    And if possible i'd like to hardcode the directory in the program (we can call the directory X for now) and to make sure it goes through subdirectories as well.

     Thanks for the help

    Thursday, August 28, 2008 12:34 PM

All replies

  • User-1501102275 posted

    I would use recursion for this scenario.

        Private Sub UpdateFilenames(ByVal path As String)
            If (System.IO.Directory.Exists(path)) Then
                Dim dir As New System.IO.DirectoryInfo(path)

                For Each sudDir As String In System.IO.Directory.GetDirectories(path)

                For Each file As System.IO.FileInfo In dir.GetFiles()
                    Dim newname As String = file.Name.Replace("$", "_")
                    newname = System.IO.Path.Combine(file.Directory.FullName, newname)
                    If (Not System.IO.File.Exists(newname)) Then
                        System.IO.File.Move(file.FullName, System.IO.Path.Combine(file.Directory.FullName, newname))
                        'Handle overwrite however you please.
                    End If

            End If
        End Sub

    Thursday, August 28, 2008 3:21 PM