使用进度条将同一文件复制到多个位置/驱动器

时间:2017-01-17 17:03:32

标签: vb.net system.io.file

我正在尝试制作一个vb.net应用程序,旨在同时将一个文件复制到多个位置。但我无法弄清楚如何阻止我收到的Dim parts As String() = targ.Split(New Char() {"\"c}) Dim filename As String = parts(parts.Count - 1) 'target folder name Dim dir_path As String = "" 'directory without target folder name Dim FolderList As New List(Of String) Dim copied As Integer = 0< For f As Integer = 0 To parts.Count - 2 dir_path += parts(f) + "\" Next Dim counter As Integer = IO.Directory.GetFiles(targ, "*.*", IO.SearchOption.AllDirectories).Length 'counts the number of files newitm.SubItems(4).Text = "Copied (0/" + counter.ToString + ")" 'displays the amount of copied files FolderList.Add(targ) 'Set first folder Do While True Dim FoldersInsideDirectory As New List(Of String) If FolderList.Count = 0 Then Exit Do 'If there is no folder to copy Exit Do Else For l As Integer = 0 To FolderList.Count - 1 Dim fileSystemInfo As System.IO.FileSystemInfo Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(FolderList(l)) Dim dest As String = FolderList(l).Replace(dir_path, "") If (Not System.IO.Directory.Exists(des + "\" + dest)) Then 'create subFolder inside directory System.IO.Directory.CreateDirectory(des + "\" + dest) End If For Each fileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos Dim destinationFileName As String = System.IO.Path.Combine(des + "\" + dest, fileSystemInfo.Name) If TypeOf fileSystemInfo Is System.IO.FileInfo Then Dim streamRead As New System.IO.FileStream(fileSystemInfo.FullName, System.IO.FileMode.Open) Dim streamWrite As New System.IO.FileStream(des + "\" + dest + "\" + fileSystemInfo.Name, IO.FileMode.Create, IO.FileAccess.Write, IO.FileShare.None) Dim lngLen As Long = streamRead.Length - 1 newitm.SubItems(3).Text = "Copy bytes : (0/" + (lngLen * 100).ToString + ")" Dim byteBuffer(1048576) As Byte 'our stream buffer Dim intBytesRead As Integer 'number of bytes read While streamRead.Position < lngLen 'keep streaming until EOF newitm.SubItems(3).Text = "Copy bytes : (" + CInt(streamRead.Position).ToString + "/" + (lngLen * 100).ToString + ")" intBytesRead = (streamRead.Read(byteBuffer, 0, 1048576)) streamWrite.Write(byteBuffer, 0, intBytesRead) streamRead.Flush() End While 'Clean up streamWrite.Flush() streamWrite.Close() streamRead.Close() copied += 1 newitm.SubItems(4).Text = "Copied (" + copied.ToString + "/" + counter.ToString + ")" Else FoldersInsideDirectory.Add(fileSystemInfo.FullName) End If Next Next FolderList.Clear() FolderList = FoldersInsideDirectory End If MsgBox("Done") Loop ,因为多个线程正在尝试访问该文件。这是我目前的代码:

{{1}}

1 个答案:

答案 0 :(得分:1)

您需要在FileShare.Read中指定FileStream's constructor

  

<强>读取

     

允许随后打开文件进行阅读。如果未指定此标志,则在文件关闭之前,任何打开文件以供阅读( 此过程或其他进程 )的请求都将失败。

Dim streamRead As New System.IO.FileStream(fileSystemInfo.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)