这不是世界上最有效的事情,但它是实现既定目标的简单方法:
Public Function SaveWithUniqueFileName(desiredFilePath As String, contents() As Byte) As String
Dim uniqueFilePath As String = Nothing
Dim suceeded As Boolean = False
For i As Integer = 1 To Integer.MaxValue
If i = 1 Then
uniqueFilePath = desiredFilePath
Else
Dim uniqueFileName As String = Path.GetFileNameWithoutExtension(desiredFilePath) & i.ToString() & Path.GetExtension(desiredFilePath)
uniqueFilePath = Path.Combine(Path.GetDirectoryName(desiredFilePath), uniqueFileName)
End If
If Not File.Exists(uniqueFilePath) Then
Try
Using stream As New FileStream(uniqueFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None)
stream.Write(contents, 0, contents.Length)
End Using
suceeded = True
Exit For
Catch ex As IOException
End Try
End If
Next
If Not suceeded Then
uniqueFilePath = Nothing
End If
Return uniqueFilePath
End Function
如果文件名不存在,该方法将保存到所需的文件名,或者如果文件名已经存在,则将唯一编号附加到文件名。例如,如果你这样称呼它:
Dim data() As Byte = {72, 101, 108, 108, 111}
Dim savedToPath As String = SaveWithUniqueFileName("C:\Test.txt", data)
If savedToPath IsNot Nothing Then
Console.WriteLine("Successfully saved to " & savedToPath)
Else
Console.WriteLine("Failed to save")
End If
有许多改进要做。它应该对它的计数有一定的限制,并且它应该比仅仅吃掉它并返回 null 更好地处理异常(理想情况下,消费代码会知道它为什么失败)。此外,它会遍历从 1 开始的所有同名文件,因此同名文件越多,运行速度就越慢。如果性能是一个问题,您可以通过某种方式同步所有客户端,这样它们就不会同时尝试保存。这可以像将单个标志文件锁定在同一文件夹中一样简单,也可以像客户端/服务器安排一样涉及,其中所有客户端都将请求发送到单个服务器,该服务器以有序的串行方式处理保存。无论哪种方式,这个简单的示例都是一个很好的起点。