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");
If you have to write a file in a background task you can write it sincronously in an async method.
the execution output will be: 1,3,2,2 end
It already does it. See for example Using Async for File Access MSDN article.
Unfortunately, the desktop APIs are a bit spotty when it comes to asynchronous file operations. As you noted, a number of the nice convenience methods do not have asynchronous equivalents. Also missing are asynchronous opening of files (which is especially useful when opening files over a network share).
I'm hoping these APIs will be added as the world moves to .NET Core.
That's the best approach right now.
Note that when using
ReadAsync
/WriteAsync
and friends, you must explicitly open the file for asynchronous access. The only way to do this (currently) is to use aFileStream
constructor overload that takes abool isAsync
parameter (passingtrue
) or aFileOptions
parameter (passingFileOptions.Asynchronous
). So you can't use the convenience open methods likeFile.Open
.Yes. There are async methods for working with the file system but not for the helper methods on the static
File
type. They are onFileStream
.So, there's no
File.ReadAllBytesAsync
but there'sFileStream.ReadAsync
, etc. For example:In .NET core (since version 2.0) there are now all the async flavors of corresponding ReadAll/WriteAll/AppendAll methods like:
https://docs.microsoft.com/en-us/dotnet/api/system.io.file.readallbytesasync?view=netcore-2.1
Unfortunately, they are still missing from .NET standard 2.0.