1

I get data from a PipeReader as a ReadOnlySequence which I need to write into a Stream, but I can't figure out how do to that? Here's my current code:

Stream blobStream = await blobClient.OpenWriteAsync(false); 

while(true)
{
    var readResult = await reader.ReadAsync();
    ReadOnlySequence<byte> buffer = readResult.Buffer;

    // here I want to write the buffer to the Stream - but how?
    // e.g. blobStream.WriteAsync(buffer) doesn't work as there is no matching method overload
}
stefan.at.kotlin
  • 15,347
  • 38
  • 147
  • 270

1 Answers1

-1

If it's writing from an Azure blob, you should use DownloadToAsync(stream)

public static async Task DownloadBlobToStreamAsync(
    BlobClient blobClient,
    string localFilePath)
{
    //This could be any Stream
    FileStream fileStream = File.OpenWrite(localFilePath);

    await blobClient.DownloadToAsync(fileStream);

    fileStream.Close();
}

To upload from a stream to blob storage use UploadAsync(stream)

public static async Task UploadFromStreamAsync(
    BlobContainerClient containerClient,
    string localFilePath)
{
    string fileName = Path.GetFileName(localFilePath);
    BlobClient blobClient = containerClient.GetBlobClient(fileName);

    //This could be any stream
    FileStream fileStream = File.OpenRead(localFilePath);
    await blobClient.UploadAsync(fileStream, true);
    fileStream.Close();
}
Bron Davies
  • 5,930
  • 3
  • 30
  • 41
  • 1
    `using FileStream fileStream =...` and remove `fileStream.Close();` – Charlieface Jul 06 '23 at 00:10
  • The PipeReader stream I have is coming from the body of an HTTP request. I also want to use a PipeReader for performance reasons. So I need PipeReader to Azure blob. – stefan.at.kotlin Jul 06 '23 at 18:09
  • @stefan.at.kotlin Just convert the PipeReader to a Stream using the AsStream() method. https://learn.microsoft.com/en-us/dotnet/api/system.io.pipelines.pipereader.asstream?view=dotnet-plat-ext-7.0 – Bron Davies Jul 06 '23 at 21:54
  • @BronDavies Thanks, didn't see that yet. But I am wondering what the version "NET platform extensions 7" in the docs means? Is that method cross platform? – stefan.at.kotlin Jul 07 '23 at 18:12
  • 1
    @stefan.at.kotlin It basically means there are extension methods available in a nuget package and not as a core framework method. See https://stackoverflow.com/questions/53097067/what-are-net-platform-extensions-on-docs-microsoft-com It seems as though these are generally considered cross-platform compatible. – Bron Davies Jul 08 '23 at 18:51