VB.NET
Private readBytes As Byte() = Nothing
Private allBytes As System.IO.MemoryStream = Nothing
Private Sub btn1_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles btn1.Click
readBytes = New Byte(4095) {}
If allBytes IsNot Nothing Then
allBytes.Close()
End If
allBytes = New System.IO.MemoryStream()
Dim fileName As String = "C:\test.txt"
Dim fs As New System.IO.FileStream(fileName, _
System.IO.FileMode.Open, _
System.IO.FileAccess.Read, _
System.IO.FileShare.Read, _
&H1000, _
True)
fs.BeginRead(readBytes, _
0, _
readBytes.Length, _
New AsyncCallback(AddressOf ReadBytesCallback), _
fs)
End Sub
Private Sub ReadBytesCallback(ByVal ar As IAsyncResult)
Dim fs As System.IO.FileStream = _
DirectCast(ar.AsyncState, System.IO.FileStream)
Dim readSize As Integer = fs.EndRead(ar)
If readSize > 0 Then
allBytes.Write(readBytes, 0, readSize)
fs.BeginRead(readBytes, _
0, _
readBytes.Length, _
New AsyncCallback(AddressOf ReadBytesCallback), _
fs)
Else
fs.Close()
End If
End Sub
C#private byte[] readBytes = null;
System.IO.MemoryStream allBytes = null;
private void btn1_Click(object sender, System.EventArgs e)
{
readBytes = new byte[0x1000];
if (allBytes != null)
{
allBytes.Close();
}
allBytes = new System.IO.MemoryStream();
string fileName = @"C:\test.txt";
System.IO.FileStream fs = new System.IO.FileStream(
fileName,
System.IO.FileMode.Open,
System.IO.FileAccess.Read,
System.IO.FileShare.Read,
0x1000,
true);
fs.BeginRead(readBytes, 0, readBytes.Length,
new AsyncCallback(ReadBytesCallback), fs);
}
private void ReadBytesCallback(IAsyncResult ar)
{
System.IO.FileStream fs =
(System.IO.FileStream)ar.AsyncState;
int readSize = fs.EndRead(ar);
if (readSize > 0)
{
allBytes.Write(readBytes, 0, readSize);
fs.BeginRead(readBytes, 0, readBytes.Length,
new AsyncCallback(ReadBytesCallback), fs);
}
else
{
fs.Close();
}
}