Change File Extension on Multiple Files

不打扰是莪最后的温柔 提交于 2021-02-10 14:25:49

问题


I have some file in a folder.

D:\Text\Text.FL
D:\Text\Text1.FL
D:\Text\Text2.FL

i want to rename extension ".FL" to ".txt"
I've tried with this code

My.Computer.FileSystem.RenameFile("D:\Text\Text.fl","Text.txt")

but I want to shorten that code


回答1:


You want to shorten one line of code? You can call File.Move if you import the System.IO namespace but you would need to pass two full paths in that case. Maybe what you actually mean is that you don't want to have to write out a line like that for each file. If you want to change all ".fl" files to ".txt" in a folder then this is what I would do:

For Each filePath In Directory.GetFiles(folderPath, "*.fl")
    File.Move(filePath, Path.ChangeExtension(filePath, ".txt"))
Next



回答2:


An example usage of my file renamer method below:

Dim dInfo As New DirectoryInfo("C:\Directory")

dInfo.EnumerateFiles("*.FL", SearchOption.TopDirectoryOnly).ToList.
    ForEach(Sub(fInfo As FileInfo)
                RenameFile(fInfo.FullName, fInfo.Name, ".txt")
            End Sub)

With this:

''' <summary>
''' Renames a file.
''' </summary>
''' <param name="sourceFile">The source file.</param>
''' <param name="targetFileName">The target file name.</param>
''' <param name="targetFileExt">The target file ext.</param>
''' <exception cref="IO.FileNotFoundException">File not found.</exception>
Public Shared Sub RenameFile(ByVal sourceFile As FileInfo,
                             ByVal targetFileName As String,
                             Optional ByVal targetFileExt As String = "")

    Try
        If String.IsNullOrEmpty(targetFileExt) Then
            targetFileExt = sourceFile.Extension.Remove(0, 1)

        ElseIf targetFileExt.StartsWith("."c) Then
            targetFileExt = targetFileExt.Remove(0, 1)

        End If

        sourceFile.MoveTo(IO.Path.Combine(sourceFile.Directory.FullName,
                                     String.Format("{0}.{1}", targetFileName, targetFileExt)))

    Catch ex As Exception
        Throw

    End Try

End Sub


来源:https://stackoverflow.com/questions/29584565/change-file-extension-on-multiple-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!