我有一个流写入器,从一个文件读取并写入到另一个在中间的缓冲区…我使用fseek来查找字节位置,但是,它从字节位置写入到文件结束,我希望它从字节位置写入到x字节。我该如何指定呢?此外,文件可能很大,所以数学必须通过int64…下面是代码:
Dim bytesRead As Integer
Dim buffer(4096) As Byte
Using inFile As New System.IO.FileStream("c:some pathfolderfile1.ext", IO.FileMode.Open, IO.FileAccess.Read)
inFile.Seek(s, SeekOrigin.Current)
Using outFile As New System.IO.FileStream("c:some pathfolderfile2.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
正如@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 pathfolderfile1.ext", IO.FileMode.Open, IO.FileAccess.Read)
inFile.Seek(StartAt, IO.SeekOrigin.Begin)
Using outFile As New System.IO.FileStream("c:some pathfolderfile2.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