Asynchronous BinaryReader and BinaryWriter in .Net?

后端 未结 3 388
说谎
说谎 2021-01-11 23:40

I\'d like to read and write bytes and structured value types, asynchronously, without having to worry about decoders and byte-shifting: is there something out there that wou

3条回答
  •  一向
    一向 (楼主)
    2021-01-12 00:37

    You can use FileStream, make sure you call the constructor properly so it enables async and has a large enough buffer.

    var buffer = new byte[2048];
    
    using var r = new FileStream(
                      Path,
                      FileMode.Open, 
                      FileAccess.ReadWrite, 
                      FileShare.None, 
                      2048000, 
                      FileOptions.Asynchronous);
    
    await r.ReadAsync(buffer, 0, 2048);
    await r.Writesync(buffer);
    

    Now that you have a byte array you can have three options to convert them to objects:

    • use BitConverter
    • use BinaryFormatter and MemoryStream
    • write your own custom logic

提交回复
热议问题