我对 Azure Storage Blobs client library for .NET 的新版本很不满意.
我需要的是创建流,我可以在其中写入数据,假设流达到 4MB 的大小后,我需要上传它。我找到了 BlockBlobClient .有两种方法 CommitBlockListAsync 和 StageBlockAsync。这种方法看起来像我需要的,但我找不到一些使用示例。
你知道一些类似于我的需求的场景吗?或者你能帮我了解这个客户吗?
我需要这样的东西,每4MB阶段,清除流并继续编写:
public class MyStreamWrapper : Stream
{
readonly BlockBlobClient _blockBlobClient;
readonly Stream _wrappedStream;
bool _isCommited;
readonly List<string> _blockIds;
public MyStreamWrapper (BlockBlobClient blockBlobClient)
{
_wrappedStream = new MemoryStream();
_blockBlobClient = blockBlobClient;
_isCommited = false;
_blockIds = new List<string>();
}
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if ((_wrappedStream.Length + buffer.Length) / 1024 > 4) // check size if
{
int byteCount = (int)(_wrappedStream.Length - buffer.Length);
if (byteCount > 0)
{
_wrappedStream.Write(buffer, offset, byteCount);
offset += byteCount;
}
string base64Id = Convert.ToBase64String(buffer);
_blockIds.Add(base64Id);
_blockBlobClient.StageBlock(base64Id, _wrappedStream);
_wrappedStream.Flush();
}
await _wrappedStream.WriteAsync(buffer, offset, count, cancellationToken);
}
}
最佳答案
对于未出现在示例文件夹中的 API,请查看测试。
例如
[Test]
public async Task CommitBlockListAsync()
{
await using DisposingContainer test = await GetTestContainerAsync();
// Arrange
BlockBlobClient blob = InstrumentClient(test.Container.GetBlockBlobClient(GetNewBlobName()));
var data = GetRandomBuffer(Size);
var firstBlockName = GetNewBlockName();
var secondBlockName = GetNewBlockName();
var thirdBlockName = GetNewBlockName();
// Act
// Stage blocks
using (var stream = new MemoryStream(data))
{
await blob.StageBlockAsync(ToBase64(firstBlockName), stream);
}
using (var stream = new MemoryStream(data))
{
await blob.StageBlockAsync(ToBase64(secondBlockName), stream);
}
// Commit first two Blocks
var commitList = new string[]
{
ToBase64(firstBlockName),
ToBase64(secondBlockName)
};
await blob.CommitBlockListAsync(commitList);
// Stage 3rd Block
using (var stream = new MemoryStream(data))
{
await blob.StageBlockAsync(ToBase64(thirdBlockName), stream);
}
// Assert
Response<BlockList> blobList = await blob.GetBlockListAsync(BlockListTypes.All);
Assert.AreEqual(2, blobList.Value.CommittedBlocks.Count());
Assert.AreEqual(ToBase64(firstBlockName), blobList.Value.CommittedBlocks.First().Name);
Assert.AreEqual(ToBase64(secondBlockName), blobList.Value.CommittedBlocks.ElementAt(1).Name);
Assert.AreEqual(1, blobList.Value.UncommittedBlocks.Count());
Assert.AreEqual(ToBase64(thirdBlockName), blobList.Value.UncommittedBlocks.First().Name);
}
https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/storage/Azure.Storage.Blobs/tests/BlockBlobClientTests.cs
还要熟悉 REST API,客户端库是其包装器。您正在使用“较低级别”的 API 方法,该方法直接映射到 Put Block和 Put Block List REST API。
关于c# - Azure blob 存储 V12 - 使用专用类 BlockBlobStorage 的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60601736/