Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the .net framework provides async methods for working with the file-system?

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"); 
like image 392
BendEg Avatar asked Mar 02 '16 14:03

BendEg


People also ask

How does .NET async work?

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.

What is the use of async and await in .NET core?

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.

What is async in dotnet?

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.

Is .NET core async?

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.


2 Answers

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); } 
like image 81
i3arnon Avatar answered Sep 21 '22 01:09

i3arnon


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);     }; } 
like image 39
Matías Fidemraizer Avatar answered Sep 19 '22 01:09

Matías Fidemraizer