我有以下代码来删除文件名中的无效字符。
Imports System.IO
Imports System.Text.RegularExpressions
Public Class Form1
Dim fp As String
Private Sub b1_Click(sender As Object, e As EventArgs) Handles b1.Click
If (FolderBrowserDialog1.ShowDialog() = DialogResult.OK) Then
fp = FolderBrowserDialog1.SelectedPath
t2.Text = fp
End If
End Sub
Private Sub b2_Click(sender As Object, e As EventArgs) Handles b2.Click
Dim files() As FileInfo = New DirectoryInfo(fp).GetFiles("*.*", IO.SearchOption.AllDirectories)
For Each file As FileInfo In files
Dim oldName = file.Name
Dim ons As String = oldName
t1.AppendText(ons + vbNewLine)
Dim newName = Regex.Replace(oldName, "[^0-9a-zA-Z.]", "-")
If oldName <> newName Then
Dim newPath = Path.Combine(file.Directory.FullName, newName)
file.MoveTo(newPath)
End If
Next
End Sub
End Class
FileInfo
似乎有问题,Regex.Replace
不能同时转换为字符串,也放弃了一些重载问题。
两者,这都是我无法理解的。
答案 0 :(得分:4)
filename
不是文件名,而是具有FileInfo
属性的Name
实例,您应该使用它。
但是除了Regex.Replace
之外,它还返回字符串,但您并未对其进行任何操作。那么,您想在这里做什么,重命名文件?
For Each file As FileInfo In files
Dim oldName = file.Name
Dim newName = Regex.Replace(oldName, "[^\w ]", "-")
If oldName <> newName Then
Dim newPath = Path.Combine(file.Directory.FullName, newName)
file.MoveTo(newPath)
End If
Next