Search code examples
vb.netfilestream

How to stop/cancel FileStream in copying VB.NET


What is the proper way to stop the whole operation of the FileStream when copying multiple files. When i call the Stop Download() function, it stops, but when i start the copy again it doesn't start like the way it was. What should i do?

code:

Private dStop As Boolean = False

Dim streamRead As FileStream
Dim streamWrite As FileStream

Public Function StopDownload()
    dStop = True
    streamWrite.Flush()
    streamWrite.Close()
    streamRead.Close()
End Function

Public Sub Copier(ByVal URL As String, ByVal Location As String) As Boolean

    streamRead = New FileStream(URL, System.IO.FileMode.Open)
    streamWrite = New FileStream(Location, System.IO.FileMode.Create)
    Dim lngLen As Long = streamRead.Length - 1
    Dim byteBuffer(1048576) As Byte
    Dim intBytesRead As Integer

     While streamRead.Position < lngLen And dStop = False 'This is where i stop the process of copying
         intBytesRead = (streamRead.Read(byteBuffer, 0, 1048576))
         streamWrite.Write(byteBuffer, 0, intBytesRead)
         Pbar1.value = CInt(streamRead.Position / lngLen * 100)
         Application.DoEvents()    'do it
     End While 

     streamWrite.Flush()
     streamWrite.Close()
     streamRead.Close()
End Sub

Solution

  • I just have to put this at the beginning my Copier Public Sub.

    dstop = False
    

    for it to start a new copying process.