Reputation: 749
I have the following code to remove the invalid characters in filename.
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
This seems to have problem with FileInfo
, which cannot be converted to string at the same time the Regex.Replace
is also giving up some overload issue.
Both, these are beyond my comprehension.
Upvotes: 0
Views: 866
Reputation: 460098
filename
is not the name of the file but a FileInfo
instance that has a Name
property which you should use instead.
But apart from that Regex.Replace
returns the string but you are not doing anything with it. So what you want to do here, rename the file?
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
Upvotes: 5