Renaming all files in a folder

2019-06-13 21:49发布

问题:

I'm wondering if it's possible to rename all the files in a folder with a simple program, using vb.NET

I'm quite green and not sure if this is even possible. Lets say there is a folder containing the files:

Text_Space_aliens.txt, fishing_and_hunting_racoons.txt and mapple.txt.

Using a few credentials:

Dim outPut as String = "TextFile_"
Dim fileType as String = ".txt"
Dim numberOfFiles = My.Computer.FileSystem.GetFiles(LocationFolder.Text)
Dim filesTotal As Integer = CStr(numberOfFiles.Count)

Will it be possible to rename these, regardless of previous name, example:

TextFile_1.txt, TextFile_2.txt & TextFile_3.txt

in one operation?

回答1:

I think this should do the trick. Use Directory.GetFiles(..) to look for specific files. Enumerate results with a for..each and move (aka rename) files to new name. You will have to adjust sourcePath and searchPattern to work for you.

Private Sub renameFilesInFolder()
    Dim sourcePath As String = "e:\temp\demo"
    Dim searchPattern As String = "*.txt"
    Dim i As Integer = 0
    For Each fileName As String In Directory.GetFiles(sourcePath, searchPattern, SearchOption.AllDirectories)
        File.Move(Path.Combine(sourcePath, fileName), Path.Combine(sourcePath, "txtFile_" & i & ".txt"))
        i += 1
    Next
End Sub

In your title you state something about chronologically, but within your question you never mentioned it again. So I did another example ordering files by creationTime.

Private Sub renameFilesInFolderChronologically()
    Dim sourcePath As String = "e:\temp\demo"
    Dim searchPattern As String = "*.txt"

    Dim curDir As New DirectoryInfo(sourcePath)

    Dim i As Integer = 0
    For Each fi As FileInfo In curDir.GetFiles(searchPattern).OrderBy(Function(num) num.CreationTime)
        File.Move(fi.FullName, Path.Combine(fi.Directory.FullName, "txtFile_" & i & ".txt"))
        i += 1
    Next
End Sub

I've never done Lambdas in VB.net but tested my code and it worked as intended. If anything goes wrong please let me know.