how to search for a specific file in blob storage - c#

I am kind of new to Blob storage and i need to access a specific file from blob storage.
i.e when i type in a specific folder it should list out all the blobs underneath it.
Can anyone help me with that
here's the code which i am trying to do.
if (AccountFileTransfer != null)
{
BlobClientFileTransfer = AccountFileTransfer.CreateCloudBlobClient();
ContainerFileTransfer = BlobClientFileTransfer.GetContainerReference(CONTAINER);
CloudBlob blob = ContainerFileTransfer.GetBlobReference(txtFileSearch.Text);
if (blob.Uri == null)
{
System.Windows.Forms.MessageBox.Show("Not a Valid blob search");
}
else
{
lvFileTransfer.Items.Add(blob.Uri);
}
}

Use Azure Search to index and search for files in Blob storage

Try this
if (AccountFileTransfer != null)
{
CloudBlobClient blobClient =
new CloudBlobClient(blobEndpoint,
new StorageCredentialsAccountAndKey(accountName, accountKey));
CloudBlobContainer container = blobClient.GetContainerReference(CONTAINER);
foreach (var blobItem in container .ListBlobs())
{
lvFileTransfer.Items.Add(blobItem .Uri);
}
}

Try this and If the blob in a Directory in container, in that case following format
container.GetBlobReference("Images/" + fileName);
public static bool BlobExists(CloudBlobContainer container, string fileName)
{
var blob = container.GetBlobReference(fileName);
try
{
blob.FetchAttributes();
return true;
}
catch (StorageException e)
{
if (e.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound)
{
return false;
}
}
return false;
}

Related

Azure Blob FIles Access and Properties - Can't Set Properties

I'm trying to access and set the cache properties of my existing blob files but it 404's when trying to set the properties. It can call FetchAttributes() just fine; but I can't figure out what I'm doing wrong here:
foreach (var b in blobs)
{
CloudBlobContainer container = bh.GetEntFileContainer(b.Id, true);
var blobFiles = container.ListBlobs(null, true);
foreach (var file in blobFiles)
{
CloudBlob blob = new CloudBlob(file.Uri);
try
{
blob.FetchAttributes();
// set cache-control header if necessary
if (blob.Properties.CacheControl != "max-age=604800, public")
{
blob.Properties.CacheControl = "max-age=604800, public";
blob.SetProperties(); //404 here.
}
}
catch (Exception e)
{
string a = "404, doesn't exist";
}
}
}
foreach (var b in blobModels)
{
var cloudBlobContainer = bh.GetEntFileContainer(b.Id, true);
IEnumerable<IListBlobItem> blobInfos = cloudBlobContainer.ListBlobs(useFlatBlobListing: true);
foreach (var blobInfo in blobInfos)
{
try
{
CloudBlockBlob blockBlob = (CloudBlockBlob)blobInfo;
var blob = cloudBlobContainer.GetBlobReferenceFromServer(blockBlob.Name);
blob.FetchAttributes();
// set cache-control header if necessary
if (blob.Properties.CacheControl != newCacheSettings)
{
blob.Properties.CacheControl = newCacheSettings;
blob.SetProperties();
}
}
catch (Exception ex)
{
// Console.WriteLine(ex.Message);
}
}

Method not found: 'Boolean Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer.CreateIfNotExists

I'm trying to create and delete blobs with the following code. Why am I getting this error? CreateIfNotExists - Method Not Found. I get the same when I try and ListBlobs.
What am I missing? What is the correct version of Microsoft.WindowsAzure.Storage
Here's my code
var storageAccount = CloudStorageAccount.Parse(BlobConnString);
var myClient = storageAccount.CreateCloudBlobClient();
var container = myClient.GetContainerReference(Mycontainer);
container.CreateIfNotExists(BlobContainerPublicAccessType.Blob);
foreach (IListBlobItem blobItem in container.ListBlobs())
{
if (blobItem is CloudBlobDirectory)
{
CloudBlobDirectory directory = (CloudBlobDirectory)blobItem;
if (directory.Uri.AbsoluteUri.Contains(NIPRprocfolder))
{
IEnumerable<IListBlobItem> blobs = directory.ListBlobs(true);
ICloudBlob bi;
foreach (var blob in blobs)
{
if (blob is CloudBlockBlob)
{
bi = blob as CloudBlockBlob;
if (bi.Name.Contains(".xml"))
{
_logger.Info($"Deleting report : {bi.Name} from {NIPRprocfolder}");
bi.DeleteIfExists();
}
}
}
}
}
}
thx

failure deleting blobs from azure storage

I am trying to delete blobs from container. The DeleteIfExits returns true but nothing happens. I check the container using Azure's portal and I can still see the blobs.
What is wrong with my code?
private static void DeleteAllFilesWithSameName(String filePath, String filename, CloudBlobContainer container)
{
String filenameWidthoutExtension = Path.GetFileNameWithoutExtension(filename);
try
{
IEnumerable<IListBlobItem> blobs = container.ListBlobs(filenameWidthoutExtension, true);
if (blobs.Count<IListBlobItem>() > 0)
{
List<string> blobNames = blobs.OfType<CloudBlockBlob>().Select(b => b.Name).ToList();
foreach (String blobName in blobNames)
{
CloudBlockBlob blockBlob = container.GetBlockBlobReference(filename);
bool isDeleted = blockBlob.DeleteIfExists();
}
}
}
catch (Exception e)
{
Console.Write(e.Data);
}
}
I believe the issue is with the logic in your code:
CloudBlockBlob blockBlob = container.GetBlockBlobReference(filename);
Shouldn't the above line be?
CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
Please try by changing your code to:
foreach (String blobName in blobNames)
{
CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
bool isDeleted = blockBlob.DeleteIfExists();
}

How to delete files from blob container?

private readonly CloudBlobContainer _blobContainer;
public void Remove()
{
if (_blobContainer.Exists())
{
_blobContainer.Delete();
}
}
How to delete not a whole container but some List<string> disks that in the container?
This is the code I use:
private CloudBlobContainer blobContainer;
public void DeleteFile(string uniqueFileIdentifier)
{
this.AssertBlobContainer();
var blob = this.blobContainer.GetBlockBlobReference(uniqueFileIdentifier);
blob.DeleteIfExists();
}
private void AssertBlobContainer()
{
// only do once
if (this.blobContainer == null)
{
lock (this.blobContainerLockObj)
{
if (this.blobContainer == null)
{
var client = this.cloudStorageAccount.CreateCloudBlobClient();
this.blobContainer = client.GetContainerReference(this.containerName.ToLowerInvariant());
if (!this.blobContainer.Exists())
{
throw new CustomRuntimeException("Container {0} does not exist in azure account", containerName);
}
}
}
}
if (this.blobContainer == null) throw new NullReferenceException("Blob Empty");
}
You can ignore the locking code if you know this isn't going to be accessed simultaneously
Obviously, you have the blobContainer stuff sorted, so all you need is that DeleteFile method without the this.AssertBlobContainer().
Remember SDK v11 has been deprecated, with SDK v12:
using Azure.Storage.Blobs;
...
BlobServiceClient blobServiceClient = new BlobServiceClient("StorageConnectionString");
BlobContainerClient cont = blobServiceClient.GetBlobContainerClient("containerName");
cont.GetBlobClient("FileName.ext").DeleteIfExists();
There's a method called DeleteIfExistis(). Returns true/false.
CloudBlockBlob blob = CloudBlobContainer.GetBlockBlobReference(fileName);
blob.DeleteIfExists();
Filename is ContainerName/FileName, if is inside folders you need to mention the folder too. Like ContainerName/AppData/FileName and will work.
A single line code to perform deletion
private static async Task DeleteBLOBFile(string blobNamewithFileExtension)
{
BlobClient blobClient = new BlobClient(blobConnectionString,containerName,blobNamewithFileExtension);
await blobClient.DeleteIfExistsAsync();
}
We can use the cloudBlobContainer.ListBlobsSegmentedAsync to list the blobs and then cast it as ICloudBlob so that you can perform the DeleteIfExistsAsync. Below is the working sample function. Hope it helps.
public async Task < bool > PerformTasks() {
try {
if (CloudStorageAccount.TryParse(StorageConnectionString, out CloudStorageAccount cloudStorageAccount)) {
var cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
var cloudBlobContainer = cloudBlobClient.GetContainerReference(_blobContainerName);
if (await cloudBlobContainer.ExistsAsync()) {
BlobContinuationToken blobContinuationToken = null;
var blobList = await cloudBlobContainer.ListBlobsSegmentedAsync(blobContinuationToken);
var cloudBlobList = blobList.Results.Select(blb = >blb as ICloudBlob);
foreach(var item in cloudBlobList) {
await item.DeleteIfExistsAsync();
}
return true;
}
else {
_logger.LogError(ErrorMessages.NoBlobContainerAvailable);
}
}
else {
_logger.LogError(ErrorMessages.NoStorageConnectionStringAvailable);
}
}
catch(Exception ex) {
_logger.LogError(ex.Message);
}
return false;
}
List<string> FileNameList = new List<string>();
FileNameList = fileName.Split(',').Where(t => t.ToString().Trim() != "").ToList();
CloudBlobClient client;
CloudBlobContainer container;
CloudBlockBlob blob;
string accessKey;
string accountName;
string connectionString;
accessKey = Environment.GetEnvironmentVariable("StorageAccountaccessKey");
accountName = Environment.GetEnvironmentVariable("StorageAccountName");
connectionString = Environment.GetEnvironmentVariable("StorageAccountConnectionString");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
client = storageAccount.CreateCloudBlobClient();
string containerName = tenantId;
container = client.GetContainerReference(containerName);
foreach(var file in FileNameList)
{
blob = container.GetBlockBlobReference(file);
blob.DeleteIfExists();
}

Azure Blob Storage list container and blobs

I am working on a Azure Storage project where i need to upload and download blobs in a container and list the container and blob in a listbox. I am unable to display the container and the blobs in my listbox.
This is my code to List:
And finally the code behind the interface where i call my upload, download and list methods:
The reason why you don't see any result when you click on Button3 in your webform is because you don't get back any data from the ListBlob method.
Change the ListBlob method to return a result like:
public List<string> GetBlobs()
{
List<string> blobs = new List<string>();
// 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");
// Loop over items within the container and output the length and URI.
foreach (IListBlobItem item in container.ListBlobs(null, false))
{
if (item.GetType() == typeof (CloudBlockBlob))
{
CloudBlockBlob blob = (CloudBlockBlob) item;
blobs.Add(string.Format("Block blob of length {0}: {1}", blob.Properties.Length, blob.Uri));
}
else if (item.GetType() == typeof (CloudPageBlob))
{
CloudPageBlob pageBlob = (CloudPageBlob) item;
blobs.Add(string.Format("Page blob of length {0}: {1}", pageBlob.Properties.Length, pageBlob.Uri));
}
else if (item.GetType() == typeof (CloudBlobDirectory))
{
CloudBlobDirectory directory = (CloudBlobDirectory) item;
blobs.Add(string.Format("Directory: {0}", directory.Uri));
}
}
return blobs;
}
Than in your webform, I assume you have a ListBox with the name ListBox1. Call the method like:
protected void Button3_Click(object sender, EventArgs e)
{
ListBox1.DataSource = GetBlobs();
ListBox1.DataBind();
}
It isn't clear to me what problem you are experiencing as you haven't explained fully. Listing blobs within a container including paging support is demonstrated in the following code extracted from this sample.
BlobContinuationToken token = null;
do
{
BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(token);
token = resultSegment.ContinuationToken;
foreach (IListBlobItem blob in resultSegment.Results)
{
// Blob type will be CloudBlockBlob, CloudPageBlob or CloudBlobDirectory
Console.WriteLine("{0} (type: {1}", blob.Uri, blob.GetType());
}
} while (token != null);

Categories