【问题标题】:How to rename files in VB.NET to have a unique suffix?如何在 VB.NET 中重命名文件以具有唯一的后缀?
【发布时间】:2012-06-02 19:38:54
【问题描述】:

我了解如何重命名 VB.NET 中的文件,正如我在帖子末尾的代码中使用的那样。但是,我想知道是否可以重命名文件,如果文件存在然后重命名并在文件名中添加 +1?

如果我运行代码。

'第一次运行

My.Computer.FileSystem.RenameFile("c:\test\test.txt", "c:\test\NewName.txt")

'再次运行它,但它应该加上+1,因为文件已经存在,所以它应该是“c:\test\NewName1.txt”

My.Computer.FileSystem.RenameFile("c:\test\test.txt", "c:\test\NewName.txt")

更新

我决定与其重命名和 +1,不如只给它加上日期戳,所以对于像我一样苦苦挣扎的人:

My.Computer.FileSystem.RenameFile("c:\test\test.txt", "Test" & Format(Date.Now, "ddMMyy") & ".txt")

【问题讨论】:

    标签: .net vb.net


    【解决方案1】:

    您需要为此编写自己的逻辑。

    File 类有很多有用的处理文件的方法。

    If File.Exists(filePath) Then
      ' Give a new name
    Else
      ' Use existing name
    End If
    

    Path 类有许多处理文件路径的方法。

    Path.GetFileNameWithoutExtension(filePath)
    

    【讨论】:

      【解决方案2】:
      If System.IO.File.Exists("c:\test\NewName.txt") Then
         ' add +1 or loop exists with increment on the end until file doesn't exist
      End If
      

      【讨论】:

      • 对不起,我无法添加编码,所以请参阅第一篇文章。
      【解决方案3】:

      newFileName 参数中无需提及完整的文件路径,只需在此处提及新文件名,否则您将得到ArgumentException

      Dim filePath As String = "C:\fingerprint1"
      
      If File.Exists(filePath) Then
      
          Dim strNewFileName As String = "Fingerprint221"
      
          My.Computer.FileSystem.RenameFile(filePath, strNewFileName)
      
       End If
      

      【讨论】:

        【解决方案4】:
           Public Sub RenameFile(ByRef FileFind As String, ByRef NewReplaceFileName As String)
                Dim Ada As String = Path.GetFileNameWithoutExtension(FileFind)
                'VS2013 Dim Ada As String = File.Exists(FileFind)
                If Ada.Length > 0 Then
                    My.Computer.FileSystem.RenameFile(FileFind, NewReplaceFileName)
                    Exit Sub
                Else
                    MsgBox("File doesn't exists")
                End If
            End Sub
        

        【讨论】:

          【解决方案5】:

          另一种重命名文件的简单方法是使用 System.IO.File 的 Move() 方法。

          例子:

          System.IO.File.Move("C:\temp\file1.txt", "C:\temp\file1_renamed.txt")
          

          【讨论】:

            猜你喜欢
            • 2021-07-24
            • 2020-10-16
            • 2022-10-14
            • 2021-04-06
            • 1970-01-01
            • 1970-01-01
            • 2020-04-11
            • 1970-01-01
            • 2012-04-17
            相关资源
            最近更新 更多