System.IO
provides File.ReadAllTextAsync
method for .Net Standard
> 2.1 and .NET Core
2.0.
If you are using C# 7.1 or higher you can use File.ReadAllTextAsync
inside Main function directly.
static async Task Main(string[] args)
{
var astr = await File.ReadAllTextAsync(@"C:\Users\User\Desktop\Test.txt");
Console.WriteLine(astr);
}
Unfortunately, If you are not using C# 7.1
or higher then you can't use Async
Main. You have to use Task.Run to calll async methods.
static void Main(string[] args)
{
var astr=Task.Run(async () =>
{
return await File.ReadAllTextAsync(@"C:\Users\User\Desktop\Test.txt");
}).GetAwaiter().GetResult();
Console.WriteLine(astr);
}
In case you are using .NET Framework
then you have to use FileStream
because System.IO
not provides File.ReadAllTextAsync
method.
private static async Task<string> ReadAllTextAsync(string filePath)
{
using (FileStream sourceStream = new FileStream(filePath,
FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize: 4096, useAsync: true))
{
StringBuilder sb = new StringBuilder();
byte[] buffer = new byte[0x1000];
int numRead;
while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
string text = Encoding.Unicode.GetString(buffer, 0, numRead);
sb.Append(text);
}
return sb.ToString();
}
}