VB.Net FileStream Exception File In use by another

34 Views Asked by At

I have VB code that opens an input file and reads it in, manipulates the data as its read and write the the data out to a second file. I have precised the code below. When I try to use the same program to open and manipulate the file that was output the first time I get an Error saying the File was in use by another process.

If I rename the file in anyway then retry the task the error does not occur. As I understood it enclosing the filestream within a USING meant that the filestreams should close be default. As you will see I have tried to force that but still the issue occurs.

It makes no odds if I close the application and try with a fresh start, the file still triggers and exception. Most code I have seen tend to discuss the topic using C language and I am not following that.

Suggestions please as I can't see why the file should be in use.
Thank you

Using destinationFileStream As New FileStream(filename2, FileMode.Create, FileAccess.Write)
    ' Create a buffer to store the read bytes
    Dim buffer(4096) As Byte
    Dim Buffer2(4096) As Byte
    Dim bytesRead As Integer

    ' Process the file byte by byte
    Do
        ' Read a chunk of bytes from the source file
        bytesRead = sourceFileStream.Read(buffer, 0, buffer.Length)

        ' If bytesRead is 0, we reached the end of the file
        If bytesRead > 0 Then
            ' do things with the data read in and put then in buffer2
            ' Write the bytes to the destination file
            destinationFileStream.Write(Buffer2, 0, bytesRead)
        End If
    Loop While bytesRead > 0
    destinationFileStream.Close()    'redundant code bit because USING forces a close 
End Using
0

There are 0 best solutions below