0

我有一个流写入器,它从一个文件读取并写入另一个文件,中间有一个缓冲区......我使用 fseek 来寻找一个字节位置,但是,它从字节位置写入文件末尾,我想要它从字节位置写入 x 字节数。我该如何指定这个?此外,文件可能很大,所以数学必须通过 int64 ......这是代码:

 Dim bytesRead As Integer
        Dim buffer(4096) As Byte
        Using inFile As New System.IO.FileStream("c:\some path\folder\file1.ext", IO.FileMode.Open, IO.FileAccess.Read)
  inFile.Seek(s, SeekOrigin.Current)
            Using outFile As New System.IO.FileStream("c:\some path\folder\file2.ext", IO.FileMode.Create, IO.FileAccess.Write)
                Do
                    bytesRead = inFile.Read(buffer, 0, buffer.Length)
                    If bytesRead > 0 Then
                        outFile.Write(buffer, 0, bytesRead)
                    End If
                Loop While bytesRead > 0
            End Using
        End Using
4

1 回答 1

0

正如@Hans 所说,您需要跟踪到目前为止已读取的字节总数,这是每次调用 Read(); 时返回的值;只是将它累积在一个变量中。您还需要考虑要读取的最后一个“块”,因为它可能小于缓冲区的大小。这个过程可能看起来像......

    Dim StartAt As Int64 = 2000
    Dim NumBytesToCopy As Int64 = 10000
    Dim TotalBytesCopied As Int64 = 0

    Dim bytesRead As Integer
    Dim buffer(4096) As Byte
    Using inFile As New System.IO.FileStream("c:\some path\folder\file1.ext", IO.FileMode.Open, IO.FileAccess.Read)
        inFile.Seek(StartAt, IO.SeekOrigin.Begin)
        Using outFile As New System.IO.FileStream("c:\some path\folder\file2.ext", IO.FileMode.Create, IO.FileAccess.Write)
            Do
                If NumBytesToCopy - TotalBytesCopied < buffer.Length Then
                    ReDim buffer(NumBytesToCopy - TotalBytesCopied)
                End If

                bytesRead = inFile.Read(buffer, 0, buffer.Length)
                If bytesRead > 0 Then
                    outFile.Write(buffer, 0, bytesRead)
                    TotalBytesCopied = TotalBytesCopied + bytesRead
                End If
            Loop While bytesRead > 0 AndAlso TotalBytesCopied < NumBytesToCopy
        End Using
    End Using
于 2013-06-01T20:48:50.140 回答