コード例 #1
0
        /// <summary>
        /// Basic operations to work with block blobs
        /// </summary>
        /// <returns>A Task object.</returns>
        private static async Task BasicStorageBlockBlobOperationsAsync()
        {
            const string ImageToUpload = "HelloWorld.png";
            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);

            try
            {
                // The call below will fail if the sample is configured to use the azurite in the connection string, but
                // the azurite is not running.
                await container.CreateIfNotExistsAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("If you're running with the default connection string, ensure you have started the Azurite emulator. Press the Windows key and type Azure Storage to select and run it from the list of apps. Then restart the sample.");
                Console.ReadLine();
                throw;
            }

            // To view the uploaded blob in a browser, you have two options. The first option is to use a Shared Access Signature (SAS) token to delegate
            // access to the resource. See the documentation links at the top for more information on SAS. The second approach is to set permissions
            // to allow public access to blobs in this container. Uncomment the line below to use this approach. Then you can view the image
            // using: https://[InsertYourblobServiceClientNameHere].blob.core.windows.net/democontainer/HelloWorld.png
            // await container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

            // Upload a BlockBlob to the newly created container
            Console.WriteLine("2. Uploading BlockBlob");
            BlobClient blobClient = container.GetBlobClient(ImageToUpload);

            // Set the blob's content type so that the browser knows to treat it as an image.
            await blobClient.UploadAsync(File.OpenRead(ImageToUpload));

            // List all the blobs in the container.
            /// Note that the ListBlobs method is called synchronously, for the purposes of the sample. However, in a real-world
            /// application using the async/await pattern, best practices recommend using asynchronous methods consistently.
            Console.WriteLine("3. List Blobs in Container");

            foreach (var blob in container.GetBlobs())
            {
                // Blob type will be BlobClient, CloudPageBlob or BlobClientDirectory
                // Use blob.GetType() and cast to appropriate type to gain access to properties specific to each type
                Console.WriteLine("- {0} (type: {1})", blob.Name, blob.GetType());
            }

            // Download a blob to your file system
            Console.WriteLine("4. Download Blob from {0}", blobClient.Uri.AbsoluteUri);
            await blobClient.DownloadToAsync(string.Format("./CopyOf{0}", ImageToUpload));

            // Create a read-only snapshot of the blob
            Console.WriteLine("5. Create a read-only snapshot of the blob");
            var blockBlobSnapshot = await blobClient.CreateSnapshotAsync();

            // Clean up after the demo. This line is not strictly necessary as the container is deleted in the next call.
            // It is included for the purposes of the example.
            Console.WriteLine("6. Delete block blob and all of its snapshots");
            await blobClient.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots);

            // Note that deleting the container also deletes any blobs in the container, and their snapshots.
            // In the case of the sample, we delete the blob and its snapshots, and then the container,
            // to show how to delete each kind of resource.
            Console.WriteLine("7. Delete Container");
            await container.DeleteIfExistsAsync();
        }
コード例 #2
0
        /// <summary>
        /// Basic operations to work with block blobs
        /// </summary>
        /// <returns>A Task object.</returns>
        private static async Task BasicStorageBlockBlobOperationsWithAccountSASAsync()
        {
            const string      ImageToUpload     = "HelloWorld.png";
            string            containerName     = ContainerPrefix + Guid.NewGuid();
            BlobServiceClient blobServiceClient = Common.CreateblobServiceClientFromConnectionString();
            // Get an account SAS token.
            Uri sasToken = GetAccountSASToken(blobServiceClient);

            // Informational: Print the Account SAS Signature and Token.
            Console.WriteLine();
            //Console.WriteLine("Account SAS Signature: " + sasToken.Signature);
            Console.WriteLine("Account SAS Token: " + sasToken.Query);
            Console.WriteLine();

            // Get the URI for the container.
            Uri containerUri = GetContainerUri(containerName);

            // Get a reference to a container using the URI and the SAS token.
            var sasUri = new UriBuilder(containerUri);

            sasUri.Query = sasToken.Query.Substring(1, sasToken.Query.Length - 1);
            var container = new BlobContainerClient(sasUri.Uri);

            try
            {
                // Create a container for organizing blobs within the storage account.
                Console.WriteLine("1. Creating Container using Account SAS");

                await container.CreateIfNotExistsAsync();
            }
            catch (RequestFailedException e)
            {
                Console.WriteLine(e.ToString());
                Console.WriteLine("If you are running with the default configuration, please make sure you have started the Azurite. Press the Windows key and type Azure Storage to select and run it from the list of applications - then restart the sample.");
                Console.ReadLine();
                throw;
            }

            try
            {
                // To view the uploaded blob in a browser, you have two options. The first option is to use a Shared Access Signature (SAS) token to delegate
                // access to the resource. See the documentation links at the top for more information on SAS. The second approach is to set permissions
                // to allow public access to blobs in this container. Uncomment the line below to use this approach. Then you can view the image
                // using: https://[InsertYourblobServiceClientNameHere].blob.core.windows.net/democontainer/HelloWorld.png
                // await container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

                // Upload a BlockBlob to the newly created container
                Console.WriteLine("2. Uploading BlockBlob");
                BlobClient blobClient = container.GetBlobClient(ImageToUpload);
                await blobClient.UploadAsync(File.OpenRead(ImageToUpload));

                // List all the blobs in the container
                Console.WriteLine("3. 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());
                }

                // Download a blob to your file system
                Console.WriteLine("4. Download Blob from {0}", blobClient.Uri.AbsoluteUri);
                await blobClient.DownloadToAsync(string.Format("./CopyOf{0}", ImageToUpload));

                // Create a read-only snapshot of the blob
                Console.WriteLine("5. Create a read-only snapshot of the blob");
                var blockBlobSnapshot = await blobClient.CreateSnapshotAsync();

                // Delete the blob and its snapshots.
                Console.WriteLine("6. Delete block Blob and all of its snapshots");
                await blobClient.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots);
            }
            catch (RequestFailedException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
            finally
            {
                // Clean up after the demo.
                // Note that it is not necessary to delete all of the blobs in the container first; they will be deleted
                // with the container.
                Console.WriteLine("7. Delete Container");
                await container.DeleteIfExistsAsync();
            }
        }