Search code examples
c#asynchronousfilesystemsasync-awaitsystem.io.file

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");

Solution

  • 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);
    }