【问题标题】:how to avoid The file already exists error in vb.net如何避免vb.net中的文件已存在错误
【发布时间】:2014-02-02 09:24:17
【问题描述】:
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

【问题讨论】:

  • 您正在尝试复制已存在于同一目录中的文件。更改目标目录或更改文件名。

标签: vb.net visual-studio-2012


【解决方案1】:

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

File.Copy(file__1, dest, True) 

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

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

【讨论】:

    猜你喜欢
    • 2014-12-18
    • 2023-03-18
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 2020-07-13
    • 2020-12-01
    • 2021-10-02
    相关资源
    最近更新 更多