Windows Azure 之 Storage Blob 常见操作

秦楚
2023-12-01

1.新建Container

public void NewContainer(string name, int access /* 2=public container, 1=public blob, 0=private */)
        {
            if (CloudStorageAccount == null) return;

            name = NormalizeContainerName(name);

            try
            {
                CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
                client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);

                CloudBlobContainer container = client.GetContainerReference(name);
                container.Create();
                BlobContainerPermissions permissions = new BlobContainerPermissions();
                switch (access)
                {
                    case 0: // Private
                        permissions.PublicAccess = BlobContainerPublicAccessType.Off;
                        break;
                    case 1: // Public Blob
                        permissions.PublicAccess = BlobContainerPublicAccessType.Blob;
                        break;
                    case 2: // Public Container
                        permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                        break;
                }
                container.SetPermissions(permissions);
                ReportSuccess("New container " + name + " created");
            }
            catch (Exception ex)
            {
                ReportException(ex);
            }
            
        }

2. 拷贝 Container

#region Copy Container

        public void CopyContainer(string name, string destName, int access)
        {
            try
            {
                ListSpinnerVisible = Visibility.Visible;
                ClearStatus();

                name = NormalizeContainerName(name);
                destName = NormalizeContainerName(destName);

                CloudBlob blob, destBlob;
                CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
                client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);

                CloudBlobContainer container = client.GetContainerReference(name);
                CloudBlobContainer destContainer = client.GetContainerReference(destName);
                destContainer.CreateIfNotExist();

                BlobContainerPermissions permissions = new BlobContainerPermissions();
                switch (access)
                {
                    case 0: // Private
                        permissions.PublicAccess = BlobContainerPublicAccessType.Off;
                        break;
                    case 1: // Public Blob
                        permissions.PublicAccess = BlobContainerPublicAccessType.Blob;
                        break;
                    case 2: // Public Container
                        permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                        break;
                }
                destContainer.SetPermissions(permissions);

                BlobRequestOptions options = new BlobRequestOptions();
                options.UseFlatBlobListing = true;
                string blobName;

                foreach (IListBlobItem blobItem in container.ListBlobs(options))
                {
                    blob = blobItem as CloudBlob;

                    blobName = BlobDescriptor.BlobName(blob);

                    destBlob = destContainer.GetBlobReference(blobName);
                    destBlob.CopyFromBlob(blob);
                }

                ReportSuccess("Container " + name + " copied to new container " + destName);
            }
            catch (Exception ex)
            {
                ReportException(ex);
            }
            
        }

        #endregion

3. 重命名 Container

        #region Rename Container

        public void RenameContainer(string name, string destName, int access)
        {
            try
            {
                ListSpinnerVisible = Visibility.Visible;
                ClearStatus();

                name = NormalizeContainerName(name);
                destName = NormalizeContainerName(destName);

                CloudBlob blob, destBlob;
                CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
                client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);

                CloudBlobContainer container = client.GetContainerReference(name);
                CloudBlobContainer destContainer = client.GetContainerReference(destName);

                try
                {
                    destContainer.FetchAttributes();
                    ReportError("Cannot rename container - the destination container '" + destName + "' already exists");
                    ListSpinnerVisible = Visibility.Collapsed;
                    return;
                }
                catch (StorageClientException)
                {
                }
                
                destContainer.Create();

                BlobContainerPermissions permissions = new BlobContainerPermissions();
                switch (access)
                {
                    case 0: // Private
                        permissions.PublicAccess = BlobContainerPublicAccessType.Off;
                        break;
                    case 1: // Public Blob
                        permissions.PublicAccess = BlobContainerPublicAccessType.Blob;
                        break;
                    case 2: // Public Container
                        permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                        break;
                }
                destContainer.SetPermissions(permissions);

                BlobRequestOptions options = new BlobRequestOptions();
                options.UseFlatBlobListing = true;
                string blobName;

                foreach (IListBlobItem blobItem in container.ListBlobs(options))
                {
                    blob = blobItem as CloudBlob;

                    blobName = BlobDescriptor.BlobName(blob);

                    destBlob = destContainer.GetBlobReference(blobName);
                    destBlob.CopyFromBlob(blob);

                    ReportSuccess("Container " + name + " renamed to " + destName);
                }

                container.Delete();
            }
            catch (Exception ex)
            {
                ReportException(ex);
            }
            
        }

4.  删除 Container

       
        public void DeleteContainer(string name)
        {
            try
            {
                ListSpinnerVisible = Visibility.Visible;
                ClearStatus();

                name = NormalizeContainerName(name);

                CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
                client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);

                CloudBlobContainer container = client.GetContainerReference(name);

                container.Delete();

                ReportSuccess("Container " + name + " deleted");
            }
            catch (Exception ex)
            {
                ReportException(ex);
            }
            
        }

5.取得Container 的访问级别

        #region Container Access Level

        public BlobContainerPublicAccessType GetContainerAccessLevel(string containerName)
        {
            CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
            client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);
            CloudBlobContainer container = client.GetContainerReference(containerName);
            BlobContainerPermissions permissions = container.GetPermissions();
            return permissions.PublicAccess;
        }

        public void SetContainerAccessLevel(string containerName, BlobContainerPublicAccessType accessType)
        {
            CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
            client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);
            CloudBlobContainer container = client.GetContainerReference(containerName);
            BlobContainerPermissions permissions = container.GetPermissions();
            permissions.PublicAccess = accessType;
            container.SetPermissions(permissions);
        }

        #endregion

6. 新建 Blob

        #region New Blob

        public void NewBlockBlob(string containerName, string blobName, string textContent)
        {
            if (CloudStorageAccount == null) return;

            try
            {
                ClearStatus();

                containerName = NormalizeContainerName(containerName);

                CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
                client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);

                CloudBlobContainer container = client.GetContainerReference(containerName);
                container.CreateIfNotExist();
                CloudBlob blob = container.GetBlobReference(blobName);
                if (textContent == null)
                {
                    blob.UploadByteArray(new byte[] { });
                }
                else
                {
                    blob.UploadText(textContent);
                }

                RefreshDetail(containerName);

                ReportSuccess("Block blob " + blobName + " created");
            }
            catch (Exception ex)
            {
                ReportException(ex);
            }
        }

        public void NewPageBlob(string containerName, string blobName, long size)
        {
            if (CloudStorageAccount == null) return;

            try
            {
                ClearStatus();

                containerName = NormalizeContainerName(containerName);

                CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
                client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);

                CloudBlobContainer container = client.GetContainerReference(containerName);
                container.CreateIfNotExist();
                CloudPageBlob blob = container.GetPageBlobReference(blobName);
                blob.Create(size);
                RefreshDetail(containerName);

                ReportSuccess("Page blob " + blobName + " created of size " + size.ToString() + " bytes");
            }
            catch (Exception ex)
            {
                ReportException(ex);
            }
        }

        #endregion

7.  拷贝 Blob

        #region Copy Blob

        public void CopyBlob(string containerName, string sourceBlobName, string destBlobName)
        {
            if (CloudStorageAccount == null) return;

            try
            {
                ClearStatus();
                CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
                client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);

                CloudBlobContainer container = client.GetContainerReference(containerName);
                if (container != null)
                {
                    CloudBlob blob = container.GetBlobReference(sourceBlobName);
                    CloudBlob newBlob = container.GetBlobReference(destBlobName);
                    newBlob.UploadByteArray(new byte[] { });
                    newBlob.CopyFromBlob(blob);
                }
                RefreshDetail(containerName);
                ReportSuccess("Blob " + sourceBlobName + " copied to " + destBlobName);
            }
            catch (Exception ex)
            {
                ReportException(ex);
            }
        }

        #endregion

8. 重命名Blob

#region Rename Blob

        public void RenameBlob(string containerName, string sourceBlobName, string destBlobName)
        {
            if (CloudStorageAccount == null) return;

            try
            {
                ClearStatus();
                CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
                client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);

                CloudBlobContainer container = client.GetContainerReference(containerName);
                if (container != null)
                {
                    CloudBlob blob = container.GetBlobReference(sourceBlobName);
                    CloudBlob newBlob = container.GetBlobReference(destBlobName);
                    newBlob.UploadByteArray(new byte[] { });
                    newBlob.CopyFromBlob(blob);
                    blob.Delete();
                }
                RefreshDetail(containerName);
                ReportSuccess("Blob " + sourceBlobName + " renamed to " + destBlobName);
            }
            catch (Exception ex)
            {
                ReportException(ex);
            }
        }

        #endregion

9.  删除 Blob

        #region Delete Blob

        public void DeleteBlob(string containerName, string blobName)
        {
            try
            {
                DetailSpinnerVisible = Visibility.Visible;
                ClearStatus();

                containerName = NormalizeContainerName(containerName);

                CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
                client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);

                CloudBlobContainer container = client.GetContainerReference(containerName);
                CloudBlob blob = container.GetBlobReference(blobName);

                blob.Delete();

                ReportSuccess("Blob " + blobName + " deleted");
            }
            catch (Exception ex)
            {
                ReportException(ex);
            }
            RefreshDetail(containerName);
        }

        #endregion

10. 上传 Blob

        #region Upload Blob

        public bool UploadInProgress { get; internal set; }
        private string[] UploadFileList;
        private string UploadContainerName;
        private CloudBlobContainer UploadContainer;

        public void UploadBlobs(string containerName, string[] filenames)
        {
            if (CloudStorageAccount == null || 
                filenames == null || 
                filenames.Length == 0 ||
                UploadInProgress) 
            return;

            containerName = NormalizeContainerName(containerName);


            if (filenames != null && filenames.Count() == 1)
            {
                ReportActive("Uploading Blob...");
            }
            else
            {
                ReportActive("Uploading Blobs...");
            }

            UploadInProgress = true;

            UploadFileList = filenames;

            DetailSpinnerVisible = Visibility.Visible;

            UploadContainerName = containerName;
            CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
            client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);

            UploadContainer = client.GetContainerReference(containerName);

            BackgroundWorker background = new BackgroundWorker();
            background.DoWork += new DoWorkEventHandler(Background_UploadBlobs);
            background.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Background_UploadBlobsCompleted);
            background.RunWorkerAsync();
        }

        void Background_UploadBlobs(object sender, DoWorkEventArgs e)
        {
            int pos;
            string blobName;
            int count = 0;
            int errors = 0;
            CloudBlob blob;

            try
            {
                CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
                client.Timeout = new TimeSpan(1, 0, 0);
                client.WriteBlockSizeInBytes = 4 * 1024 * 1024;
                client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);

                BlobRequestOptions options = new BlobRequestOptions();
                options.Timeout = new TimeSpan(1, 0, 0);
                options.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);
                
                if (UploadContainer != null)
                {
                    foreach (string filename in UploadFileList)
                    {
                        try
                        {
                            DetailSpinnerVisible = Visibility.Visible;
                            blobName = filename;
                            pos = blobName.LastIndexOf("\\");
                            if (pos != -1)
                            {
                                blobName = blobName.Substring(pos + 1);
                            }
                            blob = UploadContainer.GetBlobReference(blobName);
                            
                            client.ResponseReceived += new EventHandler<ResponseReceivedEventArgs>(client_ResponseReceived);
                            FileStream stream = File.OpenRead(filename);
                            blob.UploadFromStream(stream, options);
                            stream.Close();

                            if (ContentTypeMapping.SetContentTypeAutomatically)
                            {
                                string contentType = ContentTypeMapping.GetFileContentType(filename);
                                if (contentType != null)
                                {
                                    blob.Properties.ContentType = contentType;
                                    blob.SetProperties();
                                }
                            }

                            count++;
                        }
                        catch (Exception ex)
                        {
                            if (errors == 0)
                            {
                                ReportException(ex);
                            }
                            errors++;
                        }

                        RefreshDetail(UploadContainerName);
                    }

                    if (errors > 0)
                    {
                        if (count > 0)
                        {
                            ReportWarning("Upload complete, " + numberof(count, "blob", "blobs") + " added, " + numberof(errors, "error", "errors"));
                        }
                        else
                        {
                            ReportError("Upload failed, " + numberof(count, "blob", "blobs") + " added, " + numberof(errors, "error", "errors"));
                        }
                    }
                    else
                    {
                        ReportSuccess("Upload complete, " + numberof(count, "blob", "blobs") + " added");
                    }
                }
            }
            catch (Exception ex)
            {
                ReportException(ex);
            }
        }

        void client_ResponseReceived(object sender, ResponseReceivedEventArgs e)
        {
        }

        void Background_UploadBlobsCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            UploadInProgress = false;
            DetailSpinnerVisible = Visibility.Collapsed;
        }

        #endregion

11. 下载 Blobs

        #region Download Blobs

        public bool DownloadInProgress { get; internal set; }
        private CloudBlob[] DownloadBlobList;
        private string[] DownloadFileList;
        private string DownloadContainerName;

        public void DownloadBlobs(string containerName, CloudBlob[] blobs, string[] filenames)
        {
            if (CloudStorageAccount == null || blobs == null) return;

            DownloadContainerName = NormalizeContainerName(containerName);
            DownloadBlobList = blobs;
            DownloadFileList = filenames;

            DetailSpinnerVisible = Visibility.Visible;

            if (blobs != null && blobs.Count() == 1)
            {
                ReportActive("Downloading Blob...");
            }
            else
            {
                ReportActive("Downloading Blobs...");
            }

            DownloadInProgress = true;

            BackgroundWorker background = new BackgroundWorker();
            background.DoWork += new DoWorkEventHandler(Background_DownloadBlobs);
            background.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Background_DownloadBlobsCompleted);
            background.RunWorkerAsync();
        }

        void Background_DownloadBlobs(object sender, DoWorkEventArgs e)
        {
            try
            {
                CloudBlob blob;
                string filename;
                int count = DownloadBlobList.Length;

                CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
                client.Timeout = new TimeSpan(1, 0, 0);
                client.WriteBlockSizeInBytes = 4 * 1024 * 1024;
                client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);

                BlobRequestOptions options = new BlobRequestOptions();
                options.Timeout = new TimeSpan(1, 0, 0);
                options.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);

                for (int i = 0; i < count; i++)
                {
                    blob = DownloadBlobList[i];
                    filename = DownloadFileList[i];

                    blob = client.GetBlobReference(blob.Uri.AbsoluteUri);

                    FileStream stream = File.OpenWrite(filename);
                    blob.DownloadToStream(stream);
                    stream.Close();
                }
                
                ReportSuccess("Download Complete");
            }
            catch (Exception ex)
            {
                ReportException(ex);
            }
        }

        void Background_DownloadBlobsCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            DownloadInProgress = false;
            DetailSpinnerVisible = Visibility.Collapsed;
        }

12.  公用方法(获取Container的访问规则、生成访问规则、设置访问规则)

        #region Shared Access Signatures

        public SharedAccessPolicies GetContainerAccessPolicies(string containerName)
        {
            SharedAccessPolicies policies = new SharedAccessPolicies();

            CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
            client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);
            CloudBlobContainer container = client.GetContainerReference(containerName);
            BlobContainerPermissions permissions = container.GetPermissions();

            if (permissions != null)
            {
                foreach (KeyValuePair<string, SharedAccessPolicy> policy in permissions.SharedAccessPolicies)
                {
                    policies.Add(policy.Key, policy.Value);
                }
            }

            return policies;
        }

        public void SetContainerAccessPolicies(string containerName, SharedAccessPolicies policies)
        {
            CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
            client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);
            CloudBlobContainer container = client.GetContainerReference(containerName);
            BlobContainerPermissions permissions = container.GetPermissions();
            permissions.SharedAccessPolicies.Clear();

            if (policies != null)
            {
                foreach (KeyValuePair<string, SharedAccessPolicy> policy in policies)
                {
                    permissions.SharedAccessPolicies.Add(policy.Key, policy.Value);
                }
            }

            container.SetPermissions(permissions);
        }

        public string GenerateSharedAccessSignature(string containerName, string blobName, 
            bool read, bool write, bool delete, bool list, DateTime startTime, DateTime endTime)
        {
            CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
            client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);
            CloudBlobContainer container = client.GetContainerReference(containerName);

            string path;

            if (string.IsNullOrEmpty(blobName))
            {
                path = container.Attributes.Uri.AbsoluteUri;
            }
            else
            {
                CloudBlob blob = container.GetBlobReference(blobName);
                path = blob.Attributes.Uri.AbsoluteUri;
            }

            SharedAccessPermissions permissions = new SharedAccessPermissions();
            if (read) permissions |= SharedAccessPermissions.Read;
            if (write) permissions |= SharedAccessPermissions.Write;
            if (delete) permissions |= SharedAccessPermissions.Delete;
            if (list) permissions |= SharedAccessPermissions.List;

            SharedAccessPolicy policy = new SharedAccessPolicy()
            {
                Permissions = permissions,
                SharedAccessStartTime = startTime,
                SharedAccessExpiryTime = endTime
            };

            string queryString = container.GetSharedAccessSignature(policy);

            return path + queryString;
        }

        public string GenerateSharedAccessSignatureFromPolicy(
            string containerName, string blobName, string policyName)
        {
            CloudBlobClient client = CloudStorageAccount.CreateCloudBlobClient();
            client.RetryPolicy = RetryPolicies.Retry(20, TimeSpan.Zero);
            CloudBlobContainer container = client.GetContainerReference(containerName);

            string path;

            if (string.IsNullOrEmpty(blobName))
            {
                path = container.Attributes.Uri.AbsoluteUri;
            }
            else
            {
                CloudBlob blob = container.GetBlobReference(blobName);
                path = blob.Attributes.Uri.AbsoluteUri;
            }

            string queryString = container.GetSharedAccessSignature(new SharedAccessPolicy(), policyName);

            return path + queryString;
        }

        #endregion

        #endregion

 

 类似资料: