How to delete Azure blob from asp.net web api? - c#

Uploading images from my web api to azure blob storage works fine, altough when trying to delete them i get the following error:
"An exception of type 'Microsoft.WindowsAzure.Storage.StorageException' occurred in Microsoft.WindowsAzure.Storage.dll but was not handled in user code"
This is the code im using:
// 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();
The code im trying to use comes from: https://azure.microsoft.com/sv-se/documentation/articles/storage-dotnet-how-to-use-blobs/#delete-blobs
Any help or input highly appreciated, thanks!

You should make sure that the correct file name or container name.
I use both methods.I'm sure it works in both.
Can you try code in below line ?
var result= blockBlob.DeleteIfExists();

Related

Create container in Azure storage with c#

I have the following code:
var cloudStorageAccount = CloudStorageAccount.Parse(this._appSettings.BlobConnectionString);
this._cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer container = this._cloudBlobClient.GetContainerReference("dpd/textures/test");
await container.CreateIfNotExistsAsync();
I want to create the "test" directory inside dpd/textures/, but I keep getting this error:
The requested URI does not represent any resource on the server azure
container
What am I doing wrong?
Actually, there is no real directory in blob storage. The directory(not container) is always a part of the blob's name.
So you can just create a container like "dpd", then you can use any upload methods to upload a file like myfile.txt. During uploading file, you can specify your file name as "textures/test/myfile.txt" in your GetBlockBlobReference method. Then the directory "textures/test" is created automatically.
Simple code:
CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("test1");
var myblob = cloudBlobContainer.GetBlockBlobReference("textures/test/myfile.txt");
myblob.UploadFromFile("your file path");
Test result:
And also note that, if the blob(myfile.txt) is deleted, then the directory "textures/test" will also be removed, since it's a part name of the blob.

Unable to access Azure blob in LocalStorage via its URL

I'm creating a Web Application as part of an assignment I have. The task is to upload an audio clip to an ASP page and then a Web Job will then generate from it a 20 second sample which is then displayed on the same page. I will eventually need to deploy it to Azure but at the moment I'm using local storage with the Azure Storage Emulator.
The page loads correctly and the audio is uploading to the Blob Container okay and the samples are being generated and placed in the correct folder. However the samples aren't loading into the player and I'm not able to access these samples through the browser, even when using the URL I'm reading right off the blobs in storage.
When I enter that URL into the browser (with the Application and Web Job both running) I get this message displayed:
My first instinct was that I didn't have the necessary permissions to access the container. However as far as I can tell the permissions have been configured correctly. Below is my BlobStorageService class that handles the permissions for the containers:
namespace Sampler
{
public class BlobStorageService
{
public CloudBlobContainer getCloudBlobContainer()
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse
(ConfigurationManager.ConnectionStrings["AzureStorage"].ToString());
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("audiostorage");
if (container.CreateIfNotExists())
{
BlobContainerPermissions permissions = container.GetPermissions();
permissions.PublicAccess = BlobContainerPublicAccessType.Container;
container.SetPermissions(permissions);
}
return container;
}
}
So as far as I can tell the permissions should be Public for the whole container and the code I used for it came directly from Microsoft Docs. Any suggestions for next course of action greatly appreciated and happy to post any more code you might need to see.
It seems that there is logic issue in your code. If the container is existed, then the permisson of the container will not be public, default is private. If we try to list the blob in the private container, will get not found issue. Please have a try to use the following code. Or we could use the Microsoft Azure Storage Exploer to set the container public and try it again.
public CloudBlobContainer getCloudBlobContainer()
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["AzureStorage"].ToString());
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("audiostorage");
container.CreateIfNotExists(); // remove the if condition
BlobContainerPermissions permissions = container.GetPermissions();
permissions.PublicAccess = BlobContainerPublicAccessType.Container;
container.SetPermissions(permissions);
return container;
}

Storing a string in Azure blob storage and getting a reference to the blob with C#

guys,
I've got code making an API call, getting JSON back, parsing it and storing it in an SQL table. Now I'd like to take that JSON and also save it in Azure blob storage, then save a reference to it in the SQL table as a separate field.
So far, I've got this:
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("MyConnectionString"));
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("mydata");
CloudBlockBlob blockBlob = container.GetBlockBlobReference(dataString);
blockBlob.UploadTextAsync(resultContent);
What can I save as the reference string, for future retrieval of the blob? Is it blockBlob?
Every blob will have a uri like:
https://<yourstorageaccountname>.blob.core.windows.net/containername/blobname
This is what you would store in your database. You can even use this uri to provide a direct link, within your app, to an end-user directly (e.g. as a link in a web page). Note: for the direct-link to work externally (e.g. without storage account credentials), the container would need to be public, or you'd need to create a Shared Access Signature to allow for temporary public access, if it's in a private container.
Arguably, you can store just the container/blob name, but then, if you have multiple storage accounts, you'll need to know which one you stored it in.
Your code can be changed like following:
CloudBlockBlob blockBlob = container.GetBlockBlobReference("datastring.json");
You can later retrieve this with the same name i.e. datastring.json, and you can save the same blob name in your database.

Uploading a file to Azure using UploadFromFile

I have an ASP.NET Web Forms application.
In one of my form, I am downloading a PDF from Azure and it is displayed using rasteredge (a PDF Viewer), this allow me to add and save annotation on the PDF.
The file with annotation is then saved in a folder at the root of my application (RasterEdge_Cache).
I would like to upload the PDF back into Azure, using the UploadFromFile function.
This is the function that I am using:
public static void UploadFile(DTO.BlobUpload b)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["SN_ZEUXYS"]);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(b.Container);
CloudBlockBlob blockBlob = container.GetBlockBlobReference(b.FileName);
// b.FilePath = "~/RasterEdge_Cache/193304798925/output/A-0002-00008-00205Anno.pdf"
blockBlob.UploadFromFile(b.FilePath);
}
This is the error message that I get:
An exception of type 'System.IO.DirectoryNotFoundException' occurred
in mscorlib.dll but was not handled in user code Additional
information: Could not find a part of the path 'C:\Program Files
(x86)\IIS
Express\~\RasterEdge_Cache\193304798925\output\A-0002-00008-00205Anno.pdf'.
I assume that the file path is not correct, what path should I use, or am I using UploadFromFile correctly?
Thank you for your help.
Your file path is a relative path so you should specify where exactly it relates to. Consider using Server.MapPath method to find out its physical path to the root of the application on your server.
HttpContext httpContext = HttpContext.Current;
HttpServerUtility server = httpContext.Server;
b.FilePath = server.MapPath("~/RasterEdge_Cache/193304798925/X.pdf")
An exception of type 'Microsoft.WindowsAzure.Storage.StorageException' occurred in Microsoft.WindowsAzure.Storage.dll but was not handled in user code Additional information: The remote server returned an error: (404) Not Found. So the question is, am I using the correct function: UploadFromFile? blockBlob.UploadFromFile(b.FilePath);
According to this article, the "The remote server returned an error: (404) Not Found." occurs when a upload operation against a container fails because the container or the blob is not found.
So I suggest you could firstly check the "b.Container,b.FileName"'s value is existing or you could use CreateIfNotExists method.
More details, you could refer to below codes.Hope it gives you some tips.
protected void Button5_Click(object sender, EventArgs e)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("connection string");
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
//check the b.Container value is right and exists
CloudBlobContainer container = blobClient.GetContainerReference("foobar");
CloudBlockBlob blockBlob = container.GetBlockBlobReference("TestFile.pdf");
HttpContext httpContext = HttpContext.Current;
HttpServerUtility server = httpContext.Server;
string FilePath = server.MapPath("~/test/TestFile.pdf");
//by using this code will create the container if not exists
container.CreateIfNotExists();
blockBlob.UploadFromFile(FilePath);
}

How to create a XML file in azure storage?

I'm new to Azure storage.I want to create a container and also a blob(XML file or whatever) in it. Here is the code for creating a container but I'm having trouble how to create XML (not upload form local).
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve a reference to a container.
CloudBlobContainer container = blobClient.GetContainerReference("XXXXXXXX");
// Create the container if it doesn't already exist.
container.CreateIfNotExists();
Anyone can provide some code example would be great!!
Thanks a lot!
Once you are done with the above code to get reference of a Container, do the below:
//Create reference to a Blob that May or Maynot exist under the container
CloudBlockBlob blockBlob = container.GetBlockBlobReference("something.xml");
// Create or overwrite the "something.xml" blob with contents from a string
string s = "your XML";
await blockBlob.UploadTextAsync(s);

Categories