Does the .net framework has an async
built-in library/assembly which allows to work with the file system (e.g. File.ReadAllBytes
, File.WriteAllBytes
)?
Or do I have to write my own library using the async
Methods of StreamReader
and StreamWriter
?
Something like this would be pretty nice:
var bytes = await File.ReadAllBytes("my-file.whatever");
The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete.
The async and await keywordsAn asynchronous method is one that is marked with the async keyword in the method signature. It can contain one or more await statements. It should be noted that await is a unary operator — the operand to await is the name of the method that needs to be awaited.
C# asynchronous method is a special method that executes asynchronously. C# provides async modifier to make a method asynchronous. It is used to perform asynchronous tasks. C# await expression is used to suspend the execution of a method.
NET Core C# we make use of async and await keywords to implement asynchronous programming. For any method to be asynchronous we have to add the async keyword in the method definition before the return type of the method. Also, it is general practice to add Async to the name of the method if that method is asynchronous.
Does the .net framework has an async built-in library/assembly which allows to work with the file system
Yes. There are async methods for working with the file system but not for the helper methods on the static File
type. They are on FileStream
.
So, there's no File.ReadAllBytesAsync
but there's FileStream.ReadAsync
, etc. For example:
byte[] result; using (FileStream stream = File.Open(@"C:\file.txt", FileMode.Open)) { result = new byte[stream.Length]; await stream.ReadAsync(result, 0, (int)stream.Length); }
It already does it. See for example Using Async for File Access MSDN article.
private async Task WriteTextAsync(string filePath, string text) { byte[] encodedText = Encoding.Unicode.GetBytes(text); using (FileStream sourceStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true)) { await sourceStream.WriteAsync(encodedText, 0, encodedText.Length); }; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With