using System; using System.IO; using System.Threading.Tasks; public class Program { public async TaskReadFileAsync(string filePath) { using (StreamReader sr = new StreamReader(filePath)) { string content = await sr.ReadToEndAsync(); return content; } } public static void Main() { Program p = new Program(); Task t = p.ReadFileAsync("sample.txt"); Console.WriteLine(t.Result); } }
using System; using System.IO; using System.Threading.Tasks; public class Program { public async TaskThis example demonstrates how to use the ReadToEndAsync method to read the contents of a memory stream asynchronously and return it as a string. The memory stream is created and initialized with some text. The ReadStreamAsync method takes a Stream argument and reads from it using the StreamReader class. The Main method calls this method with the memory stream and waits for it to complete before printing the stream contents to the console. Package library: System.Runtime.Extensions.ReadStreamAsync(Stream stream) { using (StreamReader sr = new StreamReader(stream)) { string content = await sr.ReadToEndAsync(); return content; } } public static void Main() { Program p = new Program(); MemoryStream memStream = new MemoryStream(); StreamWriter sw = new StreamWriter(memStream); sw.Write("Hello, world!"); sw.Flush(); memStream.Position = 0; Task t = p.ReadStreamAsync(memStream); Console.WriteLine(t.Result); } }