Delete "subpath" from Azure Storage - azure

I know Azure doesn't have actual subpaths, but if I have for example container/projectID/iterationNumber/filename.jpg and I delete a project, how can I delete from ProjectID? Is it possible through coding?
I don't want to use the azure application as I am creating a web app.
Thanks in Advance
EDIT:
This is the code provided by Microsoft to target on specific item:
// 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("mycontainer");
// Retrieve reference to a blob named "myblob.txt".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob.txt");
// Delete the blob.
blockBlob.Delete();
SystemDesignModel
public static SystemDesign returnImageURL(IListBlobItem item)
{
if (item is CloudBlockBlob)
{
var blob = (CloudBlockBlob)item;
return new SystemDesign
{
URL = blob.Uri.ToString(),
};
}
return null;
}
}

As you know, blob storage does not have the concept of subfolders. It has just 2 level hierarchy - container & blobs. So in essence, a subfolder is just a prefix that you attach to blob name. In your example, the actual file you uploaded is filename.jpg but its name from blob storage perspective is projectID/iterationNumber/filename.jpg.
Since there is no concept of subfolder, you just can't delete it like we do on our local computer. However there's a way. Blob storage provides a way to search for blobs starting with a certain blob prefix. So what you have to do is first list all blobs that start with certain prefix (projectID in your case) and then delete the blobs one at a time returned as a result of listing operations.
Take a look at sample code below:
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
var container = storageAccount.CreateCloudBlobClient().GetContainerReference("container");
BlobContinuationToken token = null;
do
{
var listingResult = container.ListBlobsSegmented("blob-prefix (projectID in your case)", true, BlobListingDetails.None, 5000, token, null, null);
token = listingResult.ContinuationToken;
var blobs = listingResult.Results;
foreach (var blob in blobs)
{
(blob as ICloudBlob).DeleteIfExists();
Console.WriteLine(blob.Uri.AbsoluteUri + " deleted.");
}
}
while (token != null);

Related

Delete Directory containing BLOB from Logic App

The task here is to delete the folders inside the storage account from a Logic App. I am seeking a similar action as "Delete Blob" to delete the folders also. For example, directory structure is like
XYZ -> 2021-06-14 -> filename.json
I want to delete the folder itself but unable to find a direct action for the same. Any work arounds are also accepted.
Here are some links where you have some details about deletion of files or folder inside blob using Logic App
1)https://lucavallarelli.altervista.org/blog/gdpr-logic-app-delete-blob/
2)https://sameeraman.wordpress.com/2017/08/25/logic-apps-delete-files-older-than-x-days-from-a-blob-storage/
Azure Blob Storage does not really have the concept of folders. The hierarchy is very simple: storage account > container > blob.
I have 2 ways for this
WAY - 1
we can delete a specific Blob from the container by using delete method as follows:
public void DeleteBlob()
{
var _containerName = "appcontainer";
string _storageConnection = CloudConfigurationManager.GetSetting("StorageConnectionString");
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(_storageConnection);
CloudBlobClient _blobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer _cloudBlobContainer = _blobClient.GetContainerReference(_containerName);
CloudBlockBlob _blockBlob = _cloudBlobContainer.GetBlockBlobReference("f115a610-a899-42c6-bd3f-74711eaef8d5-.jpg");
//delete blob from container
_blockBlob.Delete();
}
Delete Action will be:
public ActionResult DeleteBlob()
{
imageService.DeleteBlob();
return View();
}
WAY - 2
Listing the blobs within the required container, you can then delete them individually
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("your storage account");
CloudBlobContainer container = storageAccount.CreateCloudBlobClient().GetContainerReference("pictures");
foreach (IListBlobItem blob in container.GetDirectoryReference("users").ListBlobs(true))
{
if (blob.GetType() == typeof(CloudBlob) || blob.GetType().BaseType == typeof(CloudBlob))
{
((CloudBlob)blob).DeleteIfExists();
}
}
For further more analysis you can refer the following links link 1 link 2.

Deleting entire directories using azure blob storage api

I am using the Azure object store in the following manner:
I have one container, and beneath it many blobs in a directory structure.
I am using Azure Blob Storage api to manage it.
Is there a way to delete an entire directory?
Do I really need to list all the blobs under it and then delete them one by one?
Is there a workaround like deleting all blobs with the same uri prefix (again, without listing them and then deleting them one by one)?
I don't know if there is a new solution, but we did that using https://msdn.microsoft.com/library/microsoft.windowsazure.storage.blob.cloudblobcontainer.listblobs.aspx - if we see what is going on with Fiddler, there are only prefix-ed blobs returned. Please see if that will work for you:
static void GetBlobsByPrefix(string Container, string Prefix)
{
if (!string.IsNullOrEmpty(Prefix))
{
var _Container = GetBlobContainer(Container);
var _Blobs = _Container.ListBlobs(Prefix, true);
foreach (IListBlobItem blob in _Blobs)
{
....
}
}
}
static CloudBlobContainer GetBlobContainer(string container)
{
CloudStorageAccount _StorageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("rus_AzureStorageConnectionString"));
CloudBlobClient _BlobClient = _StorageAccount.CreateCloudBlobClient();
CloudBlobContainer _Container = _BlobClient.GetContainerReference(container);
return _Container;
}
You can delete the container and all your blobs will be deleted. Containers on Azure Storage act as a "folder" for your blobs.

cannot able to get file name from azure blob container

I have one azure container which is public to all and i want to retrieve filename present in that public container.
Here is My code.
// Retrieve storage account from connection string.
var storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["AzureWebJobsStorage"].ToString());
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference(sourceurl); //my path from where i have to get filename
//here i got 400 bad request error.
var blobs = container.ListBlobs(null, true, BlobListingDetails.All).Cast<CloudBlockBlob>().ToList();
foreach (var blockBlob in blobs)
{
Console.WriteLine("Name: " + blockBlob.Name);
Console.WriteLine("Size: " + blockBlob.Properties.Length);
Console.WriteLine("Content type: " + blockBlob.Properties.ContentType);
Console.WriteLine("Download location: " + blockBlob.Uri);
Console.WriteLine("=======================================");
}
Based on your comments, please change your code to something like the following:
CloudBlobContainer container = blobClient.GetContainerReference("vcmobilesiteiislogs");
var blobs = container.ListBlobs("VCMOBILESITE/2015/07/10/10/", true, BlobListingDetails.All).Cast<CloudBlockBlob>().ToList();
Essentially vcmobilesiteiislogs is your container and you want to fetch blobs names of which start with VCMOBILESITE/2015/07/10/10/ (or in other words in that sub folder though I must state that blob storage does not have a concept of folders. You just create an illusion of folder hierarchy by prefixing the blob with some name that you want to use as a folder name).
So you would pass VCMOBILESITE/2015/07/10/10/ as blob prefix when you call ListBlobs method on your container.

Unable to download the files which were uploaded to the blob storage

I have created container on azure storage and with code below made it work to upload my files(blobs) in container. Now it says upload was successful however I can't figure out how to reach those files to download it. There is no documentation on the internet about it.
Any help would be appreciated to solve it.
// create Azure Storage
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=bireddy;AccountKey=8OMbjBeJR+SIYaSt0YtBUzivLKPX5ZbsGJeEY9vsX0BPbX3uy9KxOckK7LuLeH3ZbOh+NoEaiEIV/NWvZbFOrA==");
// create a blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// create a container
CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");
// make it public
container.SetPermissions(
new BlobContainerPermissions {
PublicAccess = BlobContainerPublicAccessType.Container
});
// create a block blob
CloudBlockBlob blockBlob = container.GetBlockBlobReference(FileUpload1.FileName);
// upload to Azure Storage
// this has to be changed sometime later
blockBlob.Properties.ContentType = FileUpload1.PostedFile.ContentType;
blockBlob.UploadFromStream(FileUpload1.FileContent);
Grateful to your discussion.
There are a number of options to download your blobs:
Using PowerShell: See the Azure Storage Powershell guide here:
http://azure.microsoft.com/en-us/documentation/articles/storage-powershell-guide-full/
Using Command Line: See the documentation for the AzCopy tool here:
http://aka.ms/azcopy
Using your C# code: There is a guide here, that includes a section on how to download blobs:
http://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-blobs/
Using GUI-based explorers: There are a number of third-party explorers, some of them are listed here:
http://blogs.msdn.com/b/windowsazurestorage/archive/2014/03/11/windows-azure-storage-explorers-2014.aspx
// Parse the connection string and return a reference to the storage account.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
//Create the Blob service client
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve a reference to a container.
CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");
// Retrieve reference to a blob named
CloudBlockBlob blockBlob2 = container.GetBlockBlobReference(document);
//using (var np = File.Open(#"C:\mydocuments\"+ document, FileMode.Create))
// blockBlob2.DownloadToStream(np, null, options, null);
byte[] fileBytes;
using (var fileStream = new MemoryStream())
{
blockBlob2.DownloadToStream(fileStream, null, options, null);
fileBytes = fileStream.ToArray();
}
return fileBytes;

Can't rename blob file in Azure Storage

I am trying to rename blob in azure storage via .net API and it is I am unable to rename a blob file after a day : (
Here is how I am doing it, by creating new blob and copy from old one.
var newBlob = blobContainer.GetBlobReferenceFromServer(filename);
newBlob.StartCopyFromBlob(blob.Uri);
blob.Delete();
There is no new blob on server so I am getting http 404 Not Found exception.
Here is working example that i have found but it is for old .net Storage api.
CloudBlob blob = container.GetBlobReference(sourceBlobName);
CloudBlob newBlob = container.GetBlobReference(destBlobName);
newBlob.UploadByteArray(new byte[] { });
newBlob.CopyFromBlob(blob);
blob.Delete();
Currently I am using 2.0 API. Where I am I making a mistake?
I see that you're using GetBlobReferenceFromServer method to create an instance of new blob object. For this function to work, the blob must be present which will not be the case as you're trying to rename the blob.
What you could do is call GetBlobReferenceFromServer on the old blob, get it's type and then either create an instance of BlockBlob or PageBlob and perform copy operation on that. So your code would be something like:
CloudBlobContainer blobContainer = storageAccount.CreateCloudBlobClient().GetContainerReference("container");
var blob = blobContainer.GetBlobReferenceFromServer("oldblobname");
ICloudBlob newBlob = null;
if (blob is CloudBlockBlob)
{
newBlob = blobContainer.GetBlockBlobReference("newblobname");
}
else
{
newBlob = blobContainer.GetPageBlobReference("newblobname");
}
//Initiate blob copy
newBlob.StartCopyFromBlob(blob.Uri);
//Now wait in the loop for the copy operation to finish
while (true)
{
newBlob.FetchAttributes();
if (newBlob.CopyState.Status != CopyStatus.Pending)
{
break;
}
//Sleep for a second may be
System.Threading.Thread.Sleep(1000);
}
blob.Delete();
The code in OP was almost fine except that an async copy method was called. The simplest code in new API should be:
var oldBlob = cloudBlobClient.GetBlobReferenceFromServer(oldBlobUri);
var newBlob = container.GetBlobReference("newblobname");
newBlog.CopyFromBlob(oldBlob);
oldBlob.Delete();

Resources