【问题标题】:Removing invalid characters in file names删除文件名中的无效字符
【发布时间】:2018-10-09 14:34:07
【问题描述】:

我有以下代码来删除文件名中的无效字符。

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 也放弃了一些重载问题。
两者,这些都超出了我的理解范围。

【问题讨论】:

标签: vb.net file character


【解决方案1】:

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

【讨论】:

  • 我从 lineSystem.IO.File.Move(file.FullName, newPath) 中的语法 file.FullName 收到此异常未处理错误 System.NotSupportedException: 'The given path's format is not supported.'。你能帮忙吗
  • @ambrishdhaka:看编辑,可以使用FileInfo.MoveTo。如果这不起作用,这里newPath 的值是多少?使用调试器
  • @ambrishdhaka:很明显你的正则表达式是错误的。但这不是这个问题的一部分,是吗?
  • @ambrishdhaka:FileInfo 不是“格式”,它是一个类。但是您不需要它,因为 FileInfo.MoveTo 将新路径视为字符串。 docs.microsoft.com/en-us/dotnet/api/…
  • 我觉得你需要看看我上传的新鲜图片。这绝对不是关于正则表达式。
猜你喜欢
  • 2011-04-19
  • 2015-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-27
  • 2019-08-09
  • 2017-02-02
  • 2013-05-14
相关资源
最近更新 更多