如何避免vb.net中的文件已存在错误

时间:2014-02-02 09:24:17

标签: vb.net visual-studio-2012

Private Shared Sub CopyDirectory(sourcePath As String, destPath As String)
        If Not Directory.Exists(destPath) Then
            Directory.CreateDirectory(destPath)
        End If

    For Each file__1 As String In Directory.GetFiles(sourcePath)
        Dim dest As String = Path.Combine(destPath, Path.GetFileName(file__1))
        Try
            File.Copy(file__1, dest)    '<--------this part is showing error
        Catch ex As Exception
            File.Replace(file__1, dest, dest, 0)
        End Try
    Next

    For Each folder As String In Directory.GetDirectories(sourcePath)
        Dim dest As String = Path.Combine(destPath, Path.GetFileName(folder))
        CopyDirectory(folder, dest)
    Next
End Sub

1 个答案:

答案 0 :(得分:3)

您可以使用File.Copy方法的重载作为第三个参数传递True

File.Copy(file__1, dest, True) 

这将替换目标文件夹中的现有文件(如果有),而不是抛出异常。

参考:http://msdn.microsoft.com/en-us/library/9706cfs5.aspx