1

我有一个工作代码,它将获取一个文件,例如“photo.png”并将其移动到一个文件夹中。如果它已经存在,它将重命名为“1_photo.png”,但如果您有另一个照片名称“photo.png”,它会将其重命名为已经存在且无法使用的文件“1_photo.png”。我想知道解决方案是什么。

        Dim grade As String
        grade = (FolderBrowserDialog1.SelectedPath)
        grade = My.Settings.SD

        My.Computer.FileSystem.CreateDirectory(
grade + ("\Pictures"))

        Dim filePaths = IO.Directory.GetFiles(grade, "*.png")

        For Each filePath In filePaths
            Dim filename = IO.Path.GetFileName(filePath)
            Dim newPath = IO.Path.Combine(grade + ("\Pictures"), filename)

            If IO.File.Exists(newPath) Then
                Dim dr = MessageBox.Show($"File {newPath} exists, do you want to keep both files? The recently moved file will have a number added to its name", "", MessageBoxButtons.YesNoCancel)

                Select Case dr
                    Case DialogResult.Cancel
                        Continue For

                    Case DialogResult.No
                        IO.File.Delete(newPath)

                    Case DialogResult.Yes


                        If IO.File.Exists(newPath) Then
                            Dim rn As New Random
                            My.Computer.FileSystem.RenameFile(newPath, "1_" + filename)

                            IO.File.Move(filePath, newPath)

                            MessageBox.Show("Pictures Compiled and Cleaned")

                            Return
                        End If


                End Select

            End If

            IO.File.Move(filePath, newPath)
4

1 回答 1

0

您以文件存在为条件进行循环:

Dim filename = "a.png"
Dim dirname = "c:\temp"

Dim filePath = Path.Combine(dirname, filename)

Dim i as Integer = 1
While(IO.File.Exists(filePath))
  filePath = Path.Combine(dirname, i & "_" & filename)
  i += 1
End While

最终,循环会找到一个不存在的文件路径。

顺便说一下,在文件名的开头放一个数字可能是个坏主意。我建议你把它放在最后:

filePath = Path.Combine(dirname, Path.ChangeExtension(filename, i & Path.GetExtension(filename)))

这使得像 photo.png、photo.1.png、photo.2.png、photo.3.png 这样的文件......

我会将它包装在一个函数中,该函数可以找到一个不冲突的文件名:

Function GetRelatedNonExistantFilepath(Dim desiredPath as String) As String()

    Dim filename =  Path.GetFilenameWithoutExtension(desiredPath)
    Dim ext = Path.GetExtension(desiredPath)
    Dim dirname = Path.GetDirectoryName(desiredPath)

    Dim filePath = desiredPath

    Dim i as Integer = 1
    While(IO.File.Exists(filePath))
      filePath = Path.Combine(dirname, filename & "_" & i & ext)
      i += 1
    End While

    Return filePath
End Function

因此,您可以像这样使用它:

    'want to move to c:\temp\photo.png but it might exist
    Dim dest = "c:\temp\photo.png"

    Dim actualDest = GetRelatedNonExistantFilepath(dest)

    'move file to actual dest
    IO.FIle.Move(sourcePath, actualDest)
于 2020-05-30T07:04:08.313 回答