How to rename files in VB.NET to have a unique suffix?

后端 未结 5 1918
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 20:01

I understand how to rename a file in VB.NET as I use in the code at the end of my post. However, I was wondering if it\'s possible to rename a file and if the file exists th

相关标签:
5条回答
  • 2020-12-06 20:06
       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
    
    0 讨论(0)
  • 2020-12-06 20:11

    You don't need to mention the complete file path in newFileName parameter, just mention new file name here otherwise you will get 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
    
    0 讨论(0)
  • 2020-12-06 20:20

    Another simple way to rename a file is to use the Move() method of System.IO.File.

    Example:

    System.IO.File.Move("C:\temp\file1.txt", "C:\temp\file1_renamed.txt")
    
    0 讨论(0)
  • 2020-12-06 20:27

    You need to write your own logic for this.

    The File class has many useful method for dealing with files.

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

    The Path class has many methods for dealing with file paths.

    Path.GetFileNameWithoutExtension(filePath)
    
    0 讨论(0)
  • 2020-12-06 20:28
    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
    
    0 讨论(0)
提交回复
热议问题