简体   繁体   中英

VB.net rename each file in a directory

Id like to rename all my files in one specific directory. They shall all get the identical extension. I tried using a for loop:

For Each s As String In IO.Directory.GetFiles(Environ("PROGRAMFILES(x86)"), "*", IO.SearchOption.AllDirectories)
        Try
            My.Computer.FileSystem.RenameFile(s, s & ".new")
        Catch ex As Exception
        End Try

So that the name s (as string) becomes s & extension ".new" However, that didnt work.

If you had read the documentation for the RenameFile method you are calling, as you should have to begin with but especially when it didn't work, then you would know that the first argument requires the full path of the file while the second argument requires just the new name of the file. That means that you need this:

My.Computer.FileSystem.RenameFile(s, My.Computer.FileSystem.GetName(s) & ".new")

The File.Move method requires full paths in both cases because it supports renaming within the same folder and moving to a different folder. You say that you want to use RenameFile but didn't bother to note how it is different, ie it only supports renaming within the same folder so specifying that path twice is pointless and allowing different paths to be specified would cause problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM