Vb.net System.IO.IOException:进程无法访问文件';文件路径';因为另一个process.File.Copy正在使用它

Vb.net System.IO.IOException:进程无法访问文件';文件路径';因为另一个process.File.Copy正在使用它,vb.net,Vb.net,我使用File.Copy函数在For循环中将文件从一个位置复制到另一个位置,因为我们必须在200个不同的位置复制该文件。但我在过程中出错了。下面是我使用的代码。 If File.Exists(FromfileLocation) Then File.Copy(FromfileLocation, TofileLocation, True) End If 您可以用另一种方式来实现,而不会出现“被另一个进程使用”的问题 试试这个: Public Shared Sub CopyMyFil

我使用File.Copy函数在For循环中将文件从一个位置复制到另一个位置,因为我们必须在200个不同的位置复制该文件。但我在过程中出错了。下面是我使用的代码。

 If File.Exists(FromfileLocation) Then
   File.Copy(FromfileLocation, TofileLocation, True)
 End If

您可以用另一种方式来实现,而不会出现“被另一个进程使用”的问题

试试这个:

   Public Shared Sub CopyMyFile(FromfileLocation As String, TofileLocation As String)

    Try

        If File.Exists(FromfileLocation) Then
            Using fs As FileStream = File.OpenRead(FromfileLocation)
                Using sw As FileStream = File.Open(TofileLocation, FileMode.OpenOrCreate)
                    Dim b(1024 * 4) As Byte
                    Do
                        Dim readed As Integer = fs.Read(b, 0, b.Length)
                        If readed > 0 Then
                            sw.Write(b, 0, readed)
                        Else
                            Exit Do
                        End If
                    Loop
                End Using
            End Using
        End If

    Catch ioEx As FileNotFoundException
        Console.WriteLine(ioEx.Message)
    End Try

End Sub

看起来该文件是由另一个程序打开的?如果要将同一文件复制到200个不同的目标,为什么每次都要测试file.是否存在?可能测试一次,然后在循环中执行复制。在循环中少做一次IO操作可能会有所帮助,还可以检查哪个目标文件失败。如果每次都相同,则可能是写入权限问题。