예제 #1
0
        /// <summary>
        /// Basic operations to work with page blobs
        /// </summary>
        /// <returns>A Task object.</returns>
        private static async Task BasicStoragePageBlobOperationsAsync()
        {
            const string PageBlobName  = "samplepageblob";
            string       containerName = ContainerPrefix + Guid.NewGuid();

            // Retrieve storage account information from connection string
            BlobServiceClient blobServiceClient = Common.CreateblobServiceClientFromConnectionString();

            // Create a container for organizing blobs within the storage account.
            Console.WriteLine("1. Creating Container");
            BlobContainerClient container = blobServiceClient.GetBlobContainerClient(containerName);
            await container.CreateIfNotExistsAsync();

            // Create a page blob in the newly created container.
            Console.WriteLine("2. Creating Page Blob");
            PageBlobClient pageBlob = container.GetPageBlobClient(PageBlobName);
            await pageBlob.CreateAsync(512 * 2 /*size*/); // size needs to be multiple of 512 bytes

            // Write to a page blob
            Console.WriteLine("3. Write to a Page Blob");
            byte[] samplePagedata = new byte[512];
            Random random         = new Random();

            random.NextBytes(samplePagedata);
            using (var stream = new MemoryStream(samplePagedata))
            {
                await pageBlob.UploadPagesAsync(stream, 0);
            }

            // List all blobs in this container. Because a container can contain a large number of blobs the results
            // are returned in segments with a maximum of 5000 blobs per segment. You can define a smaller maximum segment size
            // using the maxResults parameter on ListBlobsSegmentedAsync.
            Console.WriteLine("4. List Blobs in Container");
            var resultSegment = container.GetBlobsAsync();

            await foreach (var blob in resultSegment)
            {
                // Blob type will be BlobClient, CloudPageBlob or BlobClientDirectory
                Console.WriteLine("{0} (type: {1}", blob.Name, blob.GetType());
            }

            // Read from a page blob
            Console.WriteLine("5. Read from a Page Blob");
            var httpRange    = new HttpRange(0, samplePagedata.Count());
            var downloadInfo = await pageBlob.DownloadAsync(httpRange);

            // Clean up after the demo
            Console.WriteLine("6. Delete page Blob");
            await pageBlob.DeleteIfExistsAsync();

            Console.WriteLine("7. Delete Container");
            await container.DeleteIfExistsAsync();
        }