Beispiel #1
0
        /// <summary>
        /// This is to delete a blob by it name
        /// By default it will check in "mycontainer" if you don't pass container name
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="containerName"></param>
        public void DeleteBlob(string fileName, string containerName = "")
        {
            if (BlobExistsOnCloud((!string.IsNullOrEmpty(containerName) ? containerName : _defaultContainerName), fileName))
            {
                if (!string.IsNullOrEmpty(containerName))
                {
                    SetContainer(containerName);
                }
                // Retrieve reference to a blob named "filename".
                CloudBlockBlob blockBlob = _container.GetBlockBlobReference(fileName);

                // Delete the blob.
                blockBlob.Delete();
            }
        }
        public static void RemoveBlobDocument(string fileUrl, string filename, string filecontainer)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));
            CloudBlobClient    blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container  =
                blobClient.GetContainerReference(filecontainer);

            string[] files = fileUrl.Split(new string[] { filecontainer }, StringSplitOptions.None);
            filename = files[1].Remove(0, 1);
            CloudBlockBlob blob = container.GetBlockBlobReference(filename);

            blob.Delete();
            // blob.OpenRead();
        }
Beispiel #3
0
        /// <summary>
        /// 刪除Blob的動作
        /// </summary>
        /// <param name="strContainer"></param>
        /// <param name="strBlobName"></param>
        public void DeleteBlob(string strContainer, string strBlobName)
        {
            // 確定容器是否存在,不存在就建立新的容器
            CloudBlobContainer container = this.CreateContainer(strContainer, new BlobContainerPermissions()
            {
                PublicAccess = BlobContainerPublicAccessType.Blob
            });

            // 刪除Blob
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(strBlobName);

            if (blockBlob != null)
            {
                blockBlob.Delete();
            }
        }
Beispiel #4
0
        public static void DeleteBlog(string FileName)
        {
            try
            {
                Blob.BlobInitialize();
                CloudBlobClient    blobClient    = Blob.blobClient;
                string             containerName = ConfigurationManager.AppSettings["AzureBlobStorageContainerName"];
                CloudBlobContainer container     = blobClient.GetContainerReference(containerName);

                CloudBlockBlob blockBlob = container.GetBlockBlobReference(FileName);
                blockBlob.Delete();
            }
            catch
            {
            }
        }
Beispiel #5
0
        internal string RenameBlob(string blobName, string newBlobName)
        {
            string status = string.Empty;

            CloudBlockBlob blobSource = cloudBlobContainer.GetBlockBlobReference(blobName);

            if (blobSource.Exists())
            {
                CloudBlockBlob blobTarget = cloudBlobContainer.GetBlockBlobReference(newBlobName);
                blobTarget.StartCopyFromBlob(blobSource);
                blobSource.Delete();
            }

            status = "Finished renaming the blob.";
            return(status);
        }
        private void DeleteFileAzure <T>(string baseFileName)
        {
            var typeDirName = typeof(T).Name.ToLower();

            // Ensure that the share exists.
            if (!_container.Exists())
            {
                return;
            }
            CloudBlockBlob blob = _container.GetBlockBlobReference(typeDirName + "/" + baseFileName);

            if (blob.Exists())
            {
                blob.Delete();
            }
        }
Beispiel #7
0
        public static void DeleteBlob(string containerName, string blobName)
        {
            var storageConStr = YJYGlobal.GetConfigurationSetting("StorageConnectionString");
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConStr);
            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();

            // Retrieve a reference to a container.
            CloudBlobContainer container = blobClient.GetContainerReference(containerName);

            CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);

            if (blockBlob.Exists())
            {
                blockBlob.Delete();
            }
        }
Beispiel #8
0
 /// <summary>
 /// Deletes the blob from the container
 /// </summary>
 /// <param name="Container"></param>
 /// <param name="RemoteFileName"></param>
 public void DeleteBlob(string container, string fileName)
 {
     try
     {
         CloudBlobClient    blobClient    = StorageAccount.CreateCloudBlobClient();
         CloudBlobContainer blobContainer = blobClient.GetContainerReference(container);
         CloudBlockBlob     blockBlob     = blobContainer.GetBlockBlobReference(fileName);
         blockBlob.Delete();
     }
     catch (StorageException ex)
     {
         var requestInformation = ex.RequestInformation;
         Trace.WriteLine(requestInformation.HttpStatusMessage);
         throw;
     }
 }
 public void DeleteBlob(string fileName)
 {
     if (FileExists(fileName))
     {
         BlockBlob = BlobContainer.GetBlockBlobReference(fileName);
         BlockBlob.Delete();
     }
     else
     {
         //NM - When you are making comments, make sure they are expressive.  It will be common for
         // people who do not know English well to be reading your code and making modifications.
         // They might not understand what 'file dne' means.
         //file dne
         //throw (new Exception("File: " + fileName + " does not exist in the directory " + BlobContainer.Uri));
     }
 }
Beispiel #10
0
        public void DeleteBlob(string BlobName, string ContainerName)
        {
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            CloudBlobContainer container = blobClient.GetContainerReference(ContainerName);

            CloudBlockBlob blockBlob = container.GetBlockBlobReference(BlobName);

            try
            {
                blockBlob.Delete();
            }
            catch (Exception)
            {
            }
        }
Beispiel #11
0
        public static void DeleteOldVHDs()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["ARMRenderStorageKey"]);
            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer  container      = blobClient.GetContainerReference("vhds");
            var properties = blobClient.GetServiceProperties();

            properties.DefaultServiceVersion = "2016-05-31";
            blobClient.SetServiceProperties(properties);
            var images = container.ListBlobs();

            foreach (var image in images)
            {
                string blobName = image.Uri.Segments[2];
                //CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
                CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);

                //Intended to check if Blob is older than 3 days and delete it.
                //However there is a known Azure bug that prevents the fetchattributes from returning the attributes.
                //I have no other ideas on how to get the last modified date. So for now I'm just deleting all blobs.
                //This should be fine because the VHDs being used have a lease on them preventing them from deletion.
                //blockBlob.FetchAttributes();
                //DateTimeOffset threeDaysAgo = DateTimeOffset.Now.AddDays(-3);
                //blockBlob.FetchAttributes();
                //DateTimeOffset? lastModified = blockBlob.Properties.LastModified;
                //if(lastModified!=null)
                //{
                //    if(threeDaysAgo>lastModified)
                //    {
                //        blockBlob.Delete();
                //    }
                //}

                //Even though there is a lease on it. Not a good idea to try and delete our production server.
                if (!blobName.Contains("Prod") && !blobName.Contains("prod"))
                {
                    try
                    {
                        blockBlob.Delete();
                    }
                    catch
                    {
                        //there was a lease on the blob
                    }
                }
            }
        }
        private void DownloadBlob(string connectionString, string containerName, string blobFilename, string filename, bool deleteAfterDownload, bool updateProgress)
        {
            if (!this.cancelled)
            {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
                CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer  container      = blobClient.GetContainerReference(containerName.ToLower());
                CloudBlockBlob      blob           = container.GetBlockBlobReference(blobFilename);
                int progressPercentage;

                // Open a stream for writing
                using (BlobStream inStream = blob.OpenRead())
                    using (FileStream outStream = new FileStream(filename, FileMode.Create))
                    {
                        // Get the attributes for this blob
                        blob.FetchAttributes();

                        long   totalSize  = blob.Properties.Length;
                        int    bufferSize = 4096;
                        long   totalRead  = 0;
                        byte[] buffer     = new byte[bufferSize];
                        while (true)
                        {
                            int read = inStream.Read(buffer, 0, buffer.Length);
                            if (read <= 0)
                            {
                                break;
                            }
                            outStream.Write(buffer, 0, read);

                            totalRead += read;

                            if (updateProgress)
                            {
                                progressPercentage = (int)(((double)totalRead / (double)totalSize) * 100);
                                OnProgress(progressPercentage);
                            }
                        }
                    };

                if (deleteAfterDownload)
                {
                    blob.Delete();
                }
            }
        }
Beispiel #13
0
        protected void btnDelete_Click1(object sender, EventArgs e)
        {
            // Retrieve storage account from connection string
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("cloudString"));

            // Create the blob client
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve reference to a previously created container
            CloudBlobContainer container = blobClient.GetContainerReference(txtContainerName.Text.ToLower().ToString());

            // Retrieve reference to a blob named "myblob.txt".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(txtDelete.Text);

            // Delete the blob.
            blockBlob.Delete();
        }
Beispiel #14
0
        public static void DeleteFile(int conflictId, string fileName)
        {
            // Retrieve storage account from connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference("conflict-nb-" + conflictId);

            // Retrieve reference to a blob named "myblob.txt".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);

            // Delete the blob.
            blockBlob.Delete();
        }
Beispiel #15
0
        private void recurseDelete(Item item)
        {
            string            filter = "PartitionKey eq '" + item.PartitionKey + "&dir;" + item.RowKey + "'";
            TableQuery <Item> query  = new TableQuery <Item>().Where(filter);

            foreach (Item entity in itemTable.ExecuteQuery(query))
            {
                if (!entity.Collection)
                {
                    CloudBlockBlob blockBlob = GetBlockBlobReference(entity.BlobName);
                    blockBlob.Delete(DeleteSnapshotsOption.None);
                }
                TableOperation deleteOperation = TableOperation.Delete(entity);
                TableResult    deleteResult    = itemTable.Execute(deleteOperation);
                recurseDelete(entity);
            }
        }
Beispiel #16
0
        public void BlockBlobDelete(string blobContainer, string fileName)
        {
            try
            {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
                CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer  container      = blobClient.GetContainerReference(blobContainer);
                CloudBlockBlob      blockBlob      = container.GetBlockBlobReference(fileName);

                blockBlob.Delete();
            }
            catch (Exception ex)
            {
                ApplicationException ae = new ApplicationException("AzureStorage * Blob delete error!! (" + ex.Message + ")", ex);
                throw ae;
            }
        }
        public void Delete(string fileName)
        {
            CloudBlockBlob blockBlob = BlobContainer.GetBlockBlobReference(fileName);

            if (FileExists(fileName))
            {
                blockBlob = BlobContainer.GetBlockBlobReference(fileName);
                blockBlob.Delete();
            }
            else
            {
                //file does not exist in container
                _Logger.Error("Attempted to delete file: {0} from {1} when it did not exist", fileName, BlobContainer.Uri);

                throw (new System.IO.FileNotFoundException("File: " + fileName + " does not exist in the directory " + BlobContainer.Uri));
            }
        }
Beispiel #18
0
        public void DeleteBlobFile(string filePath)
        {
            CloudBlobContainer container = GetCloudBlobContainer();

            CloudBlockBlob blockBlob = container.GetBlockBlobReference(filePath);

            try
            {
                if (Exists(blockBlob))
                {
                    blockBlob.Delete();
                }
            }
            catch (Exception ex)
            {
            }
        }
        public void Delete()
        {
            // Retrieve storage account from connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference("rr-container");

            // Retrieve reference to a blob named "myblob.txt".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference("rockstar.png");

            // Delete the blob.
            blockBlob.Delete();
        }
Beispiel #20
0
        public async Task <bool> MoveBlob(string originalBlob, string newBlob)
        {
            bool returnValue = true;

            this.Connect();
            CloudBlobContainer blobContainer = this.BlobClient.GetContainerReference(this.Context.StorageContainer);

            CloudBlockBlob sourceBlob = blobContainer.GetBlockBlobReference(originalBlob);
            CloudBlockBlob targetBlob = blobContainer.GetBlockBlobReference(newBlob);


            // Deal with case where the file already exists....
            if (targetBlob.Exists())
            {
                // Have to add on to the name
                int    path      = newBlob.LastIndexOf('/');
                string dirPath   = newBlob.Substring(0, path);
                string file      = newBlob.Substring(path + 1);
                int    extension = file.LastIndexOf('.');

                int additionalSuffix = 1;
                do
                {
                    String newBlobName = String.Format("{3}/{0}({1}){2}",
                                                       file.Substring(0, extension),
                                                       additionalSuffix++,
                                                       file.Substring(extension + 1),
                                                       dirPath);
                    targetBlob = blobContainer.GetBlockBlobReference(newBlobName);
                } while (targetBlob.Exists());
            }

            // Copy the file
            string result = await targetBlob.StartCopyAsync(sourceBlob.Uri);

            if (String.IsNullOrEmpty(result) || targetBlob.CopyState.Status != CopyStatus.Success)
            {
                returnValue = false;
                throw new Exception("Copy failed: " + targetBlob.CopyState.Status);
            }

            // Since an exception is thrown before here, we must be OK
            sourceBlob.Delete();

            return(returnValue);
        }
Beispiel #21
0
        public void deletefromAzure(string filename)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));
            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference(ConfigurationManager.AppSettings["AzureFolder"]);
            // Retrieve reference to a blob named "someimage.jpg".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference($"{filename}");

            // Create or overwrite the "someimage.jpg" blob with contents from an upload stream.
            if (blockBlob.Exists())
            {
                blockBlob.Delete();
            }
        }
Beispiel #22
0
        private void button6_Click(object sender, EventArgs e)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=temmblobadmin;AccountKey=+7YLZ8+YK6td1m55K0AopQBpA/Pp+0z4iBMPind6HI87jhxF9DBe+wb11BbOyZhg+DWCqtitg/iWGexBWDaUdA==");
            //blob
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            //container
            CloudBlobContainer container = blobClient.GetContainerReference("temmfile");

            var listitem = listBox1.SelectedItem;

            // var blobs = container.GetBlockBlobReference(listitem.ToString());

            CloudBlockBlob blockBlob_delete = container.GetBlockBlobReference(listitem.ToString());

            DialogResult result = MessageBox.Show("削除しますか?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);

            //何が選択されたか調べる

            if (result == DialogResult.Yes)
            {
                blockBlob_delete.Delete();


                var list            = container.ListBlobs(useFlatBlobListing: true);
                var listOfFileNames = new List <string>();



                var blobs = container.ListBlobs().OfType <CloudBlockBlob>().ToList();


                foreach (var blob in blobs)
                {
                    var blobFileName = blob.Uri.Segments.Last();

                    listOfFileNames.Add(blobFileName);
                }

                listBox1.DataSource = listOfFileNames;
            }

            else if (result == DialogResult.No)
            {
            }
        }
Beispiel #23
0
        // Delete a blob
        public bool DeleteBlob(string blobName)
        {
            try
            {
                DeleteComments(blobName);

                CloudBlockBlob blob = container.GetBlockBlobReference(blobName);
                blob.FetchAttributes();

                blob.Delete();

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Beispiel #24
0
        public bool DeleteBlob(string containerName, string fileName, string connectionString)
        {
            // Retrieve storage account from connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference(containerName);

            // Retrieve reference to a blob named "myblob.txt".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);

            // Delete the blob.
            blockBlob.Delete();
            return(true);
        }
Beispiel #25
0
        public bool Delete(string templateName)
        {
            foreach (IListBlobItem item in _TemplateContainer.ListBlobs())
            {
                if (item is CloudBlockBlob)
                {
                    CloudBlockBlob blob = (CloudBlockBlob)item;

                    if (blob.Name.ToLower() == templateName.ToLower())
                    {
                        blob.Delete();
                        return(true);
                    }
                }
            }

            return(false);
        }
        public string deleteFile(string filename)
        {
            if (!String.IsNullOrEmpty(filename))
            {
                var            currentUser  = User.Identity.GetUserId();
                var            deletingFile = db.FileNotes.First(k => k.Name == filename && k.UserId == currentUser);
                CloudBlockBlob blockBlob    = container.GetBlockBlobReference(Path.Combine(deletingFile.AspNetUsers.UserName, deletingFile.Type, deletingFile.Name));
                if (blockBlob.Exists())
                {
                    blockBlob.Delete();
                    db.FileNotes.Remove(deletingFile);
                    db.SaveChanges();
                }
                return(deletingFile.Type);
            }

            return("");
        }
Beispiel #27
0
        object UploadBlob(string blobName)
        {
            if (blobName.EndsWith("/"))
            {
                return(CreateErrorResult("Invalid blob name."));
            }

            CloudBlockBlob blob = Container.GetBlockBlobReference(blobName);

            if (blob.Exists() && blob.Properties.Length > MaxBlobSize)
            {
                blob.Delete();
                return(CreateErrorResult());
            }

            string url = GetSharedAccessSignature(blob, SharedAccessBlobPermissions.Write);

            return(CreateSuccessResult(url));
        }
Beispiel #28
0
        object CreateDirectory(string directoryName)
        {
            string blobName = $"{directoryName}/{EmptyDirDummyBlobName}";

            CloudBlockBlob blob = Container.GetBlockBlobReference(blobName);

            if (blob.Exists())
            {
                if (blob.Properties.Length > 0)
                {
                    blob.Delete();
                }
                return(CreateErrorResult());
            }

            string url = GetSharedAccessSignature(blob, SharedAccessBlobPermissions.Write);

            return(CreateSuccessResult(url));
        }
        public bool DeleteBlob(string AbsoluteUri)
        {
            try
            {
                Uri    uriObj   = new Uri(AbsoluteUri);
                string BlobName = Path.GetFileName(uriObj.LocalPath);

                // get block blob refarence
                CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(BlobName);

                // delete blob from container
                blockBlob.Delete();
                return(true);
            }
            catch (Exception ExceptionObj)
            {
                throw ExceptionObj;
            }
        }
        /*
         * Using this because MediaServiceDeleted event is not firing in v6.1.6
         *
         */

        void MediaServiceTrashed(IMediaService sender, MoveEventArgs <IMedia> e)
        {
            if (uploadEnabled)
            {
                try
                {
                    log.Info("Deleting media from Azure:" + e.Entity.Name);
                    var            path      = e.Entity.GetValue("umbracoFile").ToString();
                    CloudBlockBlob imageBlob = container.GetBlockBlobReference(StripContainerNameFromPath(path));
                    imageBlob.Delete();
                    CloudBlockBlob thumbBlob = container.GetBlockBlobReference(StripContainerNameFromPath(GetThumbPath(path)));
                    thumbBlob.Delete();
                }
                catch (Exception x)
                {
                    log.Error("Error deleting media from Azure: " + e.Entity.Name, x);
                }
            }
        }