csharp Azure存储Blob

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp Azure存储Blob相关的知识,希望对你有一定的参考价值。

CloudStorageAccount storageAccount = CloudStorageAccount.Parse("StorageConnectionString");

CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

// Create a container
CloudBlobContainer container = blobClient.GetContainerReference(containerName);
BlobRequestOptions requestOptions = new BlobRequestOptions() { RetryPolicy = new NoRetry() };
\!h await container.CreateIfNotExistsAsync(requestOptions, null);

// Uploading BlockBlob
CloudBlockBlob blockBlob = container.GetBlockBlobReference("image.png");
blockBlob.Properties.ContentType = "image/png";
\!h await blockBlob.UploadFromFileAsync("image.png");
// Also UploadFromByteArrayAsync, UploadFromStreamAsync, UploadTextAsync

// List Blobs in Container synchronously
\!h foreach (IListBlobItem blob in container.ListBlobs())
{
    // Blob type will be CloudBlockBlob, CloudPageBlob or CloudBlobDirectory
    Console.WriteLine("{0} (type: {1})", blob.Uri, blob.GetType());
}

// Download a blob to file system
\!h await blockBlob.DownloadToFileAsync(string.Format("./CopyOf{0}", "image.png"), FileMode.Create);

// Create a read-only snapshot of the blob
\!h CloudBlockBlob blockBlobSnapshot = await blockBlob.CreateSnapshotAsync(null, null, null, null);

// Delete block blob and all of its snapshots
\!h await blockBlob.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots, null, null, null);

// Note that deleting the container also deletes any blobs in the container, and their snapshots.
\!h await container.DeleteIfExistsAsync();

// Creates an Account SAS Token
SharedAccessAccountPolicy policy = new SharedAccessAccountPolicy()
{
    Permissions = SharedAccessAccountPermissions.Read | SharedAccessAccountPermissions.Write | SharedAccessAccountPermissions.List | SharedAccessAccountPermissions.Create | SharedAccessAccountPermissions.Delete,
    Services = SharedAccessAccountServices.Blob,
    ResourceTypes = SharedAccessAccountResourceTypes.Container | SharedAccessAccountResourceTypes.Object,
    SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
    Protocols = SharedAccessProtocol.HttpsOrHttp
};
\!h string sasToken = storageAccount.GetSharedAccessSignature(policy);

// Use the account SAS token
StorageCredentials accountSAS = new StorageCredentials(sasToken);
Uri containerUri = container.Uri;
CloudBlobContainer containerViaSas = new CloudBlobContainer(containerUri, accountSAS);

// Create a page blob in the newly created container.  
CloudPageBlob pageBlob = container.GetPageBlobReference(PageBlobName);
\!h await pageBlob.CreateAsync(512 * 2 /*size*/); // size needs to be multiple of 512 bytes

// Write to a page blob 
byte[] samplePagedata = new byte[512];
new Random().NextBytes(samplePagedata);
\!h await pageBlob.UploadFromByteArrayAsync(samplePagedata, 0, samplePagedata.Length);

// Read from a page blob
\!h int bytesRead = await pageBlob.DownloadRangeToByteArrayAsync(samplePagedata, 0, 0, samplePagedata.Count());
// Configures logging and metrics for Blob storage
\!h ServiceProperties serviceProperties = await blobClient.GetServicePropertiesAsync();
serviceProperties.Logging.LoggingOperations = LoggingOperations.All;
serviceProperties.Logging.RetentionDays = 14;
serviceProperties.DefaultServiceVersion = "2018-11-09";
// Set the service properties
\!h await blobClient.SetServicePropertiesAsync(serviceProperties);

// List containers beginning with the specified prefix, and without returning container metadata
\!h foreach (var container in blobClient.ListContainers(prefix, ContainerListingDetails.None, null, null))
{
    Console.WriteLine("Container:" + container.Name);
}

// Async list of containers
do
{
    // List containers beginning with the specified prefix, returning segments of 5 results each, and populating metadata. 
    \!h resultSegment = await blobClient.ListContainersSegmentedAsync(prefix, ContainerListingDetails.Metadata, 5 /* default is 5000 */, continuationToken, null, null);
    foreach (var container in resultSegment.Results)
    {
        foreach (var metadataItem in container.Metadata)
        {
            metadataItem.Key;
            metadataItem.Value;
        }
    }
    continuationToken = resultSegment.ContinuationToken;
} while (continuationToken != null);

// Fetch some container properties and write out their values.
\!h await container.FetchAttributesAsync();
Console.WriteLine("Properties for container {0}", container.StorageUri.PrimaryUri);

// Add some metadata to the container.
container.Metadata.Add("docType", "textDocuments");
container.Metadata["category"] = "guidance";

// Set the container's metadata.
\!h await container.SetMetadataAsync();

以上是关于csharp Azure存储Blob的主要内容,如果未能解决你的问题,请参考以下文章

Azure 存储 Blob 重命名

JavaScript Azure Blob 存储移动 blob

使用 azure-storage-blob 或 azure-storage 上传和删除 Azure 存储 Blob

仅从 Azure 存储 [Azure-Blob][REST] 中的 Blob 列表获取特定元数据

Azure 存储:Blob:Python:获取指示符是不是存在 Blob

请求令牌时如何在 Azure 存储 Blob 中为 REST 请求指定范围? [AZURE-BLOB][REST API]