byte[] data = new byte[1024]; FileStream fs = new FileStream("example.txt", FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true); fs.BeginRead(data, 0, data.Length, new AsyncCallback(ReadCallback), fs); ... void ReadCallback(IAsyncResult ar) { FileStream fs = (FileStream)ar.AsyncState; int bytesRead = fs.EndRead(ar); }
using (MemoryStream ms = new MemoryStream()) { byte[] buffer = Encoding.ASCII.GetBytes("Hello, World!"); ms.Write(buffer, 0, buffer.Length); ms.Seek(0, SeekOrigin.Begin); byte[] data = new byte[ms.Length]; IAsyncResult ar = ms.BeginRead(data, 0, data.Length, null, null); int bytesRead = ms.EndRead(ar); string message = Encoding.ASCII.GetString(data); }In this example, a MemoryStream is created and a message is written to it. The Seek method is called to move the position back to the beginning of the stream. The BeginRead method is called to start reading the message from the stream as bytes, and the EndRead method is used to complete the operation and return the number of bytes read. The message is then converted back to a string using the Encoding class. In both examples, the package library being used is System.IO.