使用Vb.net将txt文件从一个文件夹复制到另一个文件夹时出现错误

时间:2019-03-01 07:32:54

标签: vb.net

我正在尝试将文件从一个文件夹复制到另一个文件夹,这给另一个进程正在使用的错误,但是却在任何地方打开了。这些是txt文件。

错误:该进程无法访问文件'D:\ Vimal \ test1 \ test2.txt',因为该文件正在被另一个进程使用。

Sub MoveFile()
    Dim _sSourcePath As String = "D:\Vimal\test1"
    Dim _sDesPath As String = "D:\Vimal\test2"
    Dim _FilelstSource As New DirectoryInfo(_sSourcePath)
    Dim _FilelstDest As New DirectoryInfo(_sDesPath)
    Dim list1 = _FilelstSource.GetFiles("*.*", SearchOption.AllDirectories)
    Dim list2 = _FilelstDest.GetFiles("*.*", SearchOption.AllDirectories)
    Dim _sTempstr As String = String.Empty
    _sTempstr = "ProcessDldFiles"
    Dim myFileCompare As New FileCompare

    Try

        If list1.Count > 0 Then
            Dim _queryDiff = list1.Except(list2, myFileCompare)
            If _queryDiff.ToList.Count > 0 Then
                For Each filename As FileInfo In _queryDiff
                    ' File.Copy(filename.FullName, filename.FullName.Replace("BAMDailyFile", _sTempstr), True)
                    File.Copy(filename.FullName, Path.Combine(_sDesPath, filename.Name), True)
                Next
                ' WriteDesLog("Total No. old cases file " & Now.Date.ToString("dd/MM/yyyy") & ":" & _queryDiff.ToList.Count())
            Else
                ' WriteDesLog("No Case to Download due to difference " & Now.Date.ToString("MM/dd/yyyy"))
            End If
        End If
    Catch ex As Exception
        ' InsertErrorLog("CompareFilesToProcess", "", ex.ToString(), Date.Now.ToString())
    End Try
End Sub

Public Class FileCompare
    Implements IEqualityComparer(Of FileInfo)

Public Function Equals1(ByVal x As FileInfo, ByVal y As FileInfo) As Boolean Implements IEqualityComparer(Of FileInfo).Equals

        If (x.Name = y.Name) And (x.Length = y.Length) Then
            Return True
        Else
            Return False
        End If
    End Function

Public Function GetHashCode1(ByVal fi As FileInfo) As Integer Implements IEqualityComparer(Of FileInfo).GetHashCode
        Dim s As String = fi.Name & fi.Length
        Return s.GetHashCode()
    End Function
End Class

1 个答案:

答案 0 :(得分:0)

需要更改File.Copy的行

File.Copy(filename.FullName,Path.Combine(_sDesPath,filename.Name),True)