I have a requirement where i want to read blob and to upload in Sftp location.Blob path is available as in the format "/container/folder1/subfold1/abc.blob".I am using below code to read the blob from above blob path
BlobServiceClient blobServiceClient1 = new BlobServiceClient(connectionString);
BlobContainerClient containerClient1 = blobServiceClient1.GetBlobContainerClient(containerName);
var bname = "container/folder1/subfold1/abc.blob";
var blockBlobClient1 = containerClient1.GetBlockBlobClient(bname);
using (var uploadBlobStream = blockBlobClient1 .OpenReadAsync())
{
_sftp.Connect();
var blobPath = string.Format("{0}/{1}", remoteFilePath, "tst.txt");
_sftp.UploadFile(uploadBlobStream.Result, remoteFilePath, true);
_sftp.Disconnect();
}
But it throws error that Blob file is not present. Can anyone help on this.
You can try the following changes:
You will need to use the value of containerName instead of "container" in the path.
var bname = $"{containerName}/folder1/subfold1/abc.blob";
The OpenReadAsync method returns a Task object that represents the asynchronous operation, rather than the stream itself. You will need to await the task to get the stream, like this:
using (var uploadBlobStream = await blockBlobClient1.OpenReadAsync())
{
// ...
}
Also, it's worth noting that the UploadFile method expects a Stream object as its first argument, but you are passing it the Task object returned by OpenReadAsync. You will need to pass the stream itself, like this:
_sftp.UploadFile(uploadBlobStream, remoteFilePath, true);
Do upvote, if you found this useful. Thanks :)
i am trying to download the word document stored in azure blob container having private access and i need to convert downloaded document into byte array so that i can be able to send to react app
this is the code i am trying below
[Authorize, HttpGet("{id}/{projectphase?}")]
public async Task<ActionResult<DesignProject>> GetDesignProject(string id, string projectphase = null)
{
var blobContainerName = Startup.Configuration["AzureStorage:BlobContainerName"];
var azureStorageConnectionString = Startup.Configuration["AzureStorage:ConnectionString"];
BlobContainerClient blobContainerClient = new BlobContainerClient(azureStorageConnectionString, blobContainerName);
blobContainerClient.CreateIfNotExists();
....... // not sure how to proceed further
.......
......
return new InlineFileContentResult('here i need to return byte array???', "application/docx") { FileDownloadName = fileName };
}
I have got the full path name where the file has been stored like as below
https://xxxx.blob.core.windows.net/design-project-files/99999-99/99999-99-BOD-Concept.docx
and then i have got the file name as well 99999-99-BOD-Concept.docx
Could any one please guide me how to proceed with the next to download the document that would be very grateful to me.
Please try something like the following (untested code though):
public async Task<ActionResult<DesignProject>> GetDesignProject(string id, string projectphase = null)
{
var blobContainerName = Startup.Configuration["AzureStorage:BlobContainerName"];
var azureStorageConnectionString = Startup.Configuration["AzureStorage:ConnectionString"];
BlobContainerClient blobContainerClient = new BlobContainerClient(azureStorageConnectionString, blobContainerName);
blobContainerClient.CreateIfNotExists();
var blobClient = new BlobClient("https://xxxx.blob.core.windows.net/design-project-files/99999-99/99999-99-BOD-Concept.docx");
var blobName = blobClient.Name;
blobClient = new BlobClient(azureStorageConnectionString, blobContainerName, blobName);
using (var ms = new MemoryStream())
{
await blobClient.DownloadToAsync(ms);
return new InlineFileContentResult(ms.ToArray(), "application/docx") { FileDownloadName = fileName };
}
}
Basically what we're doing is that we're first creating a BlobClient using the URL that you have so that we can extract blob's name out of that URL (you can do URL parsing as well). Once we have the blob's name, we create a new instance of BlobClient using connection string, blob container name and blob's name.
Then we download the blob's content as stream and convert that stream to byte array (this part I am not 100% sure that my code would work) and return that byte array.
You don't really need to have this process where your react app requests to your server, so your server downloads the file and then sends it to the react app; that file in blob storage is on the web, downloadable from blob storage so it's kinda unnecessary to hassle your sevrer into being a proxy for it
If you configure public access for blobs then you just put that URL into your react app - user clicks it, bytes download. Happy days. If you have a private container you can still generate SAS URLs for the blobs
If you actually need the bytes in your react app, then just fetch it with a javascript web request - you'll need to set a CORS policy on the blob container though
If you really want to download the file to/via the server, you'll probably have to get into streaming it to the response stream connected to the react app, passed into the SOMETHING below:
BlobClient blob = blobContainerClient.GetBlobClient( BLOB NAME I.E PATH INSIDE CONTAINER);
//download to a file or stream
await blob.DownloadToAsync( SOMETHING );
I have a web api that uses a bunch of appSettings files to load test data.
I want to shift the location of that data to an Azure Blob.
Based on the test infrastructure, I'd like to convert the Blob into an IConfiguration object.
To accomplish this, I wanted to use the AddJsonStream onto a ConfigurationBuilder.
I created this method to go out and grab the blob and convert it to a stream:
public static Stream GetBlobAsStream(Uri blobURI)
{
var storageAccount = CloudStorageAccount.Parse(AZURE_STORAGE_CONNECTION_STRING);
var cloudBlobClient = storageAccount.CreateCloudBlobClient();
var cloudBlobContainer = cloudBlobClient.GetContainerReference(blobContainer);
var cloudBlob = cloudBlobContainer.GetBlockBlobReference(blobName);
var stream = cloudBlob.OpenRead();
return stream;
}
Now this method uses a bunch of hard coded constants - which I'd like to remove.
How can I remove the hard coding, and find the needed azure info based on the Environment in which it's being run?
Or have I programmed myself into a corner here?
You could try to create an instance of CloudBlockBlob using the Blob URI and Blob Client by doing something like:
public static Stream GetBlobAsStream(Uri blobURI)
{
var storageAccount = CloudStorageAccount.Parse(AZURE_STORAGE_CONNECTION_STRING);
var cloudBlobClient = storageAccount.CreateCloudBlobClient();
var cloudBlob = new CloudBlockBlob(blobURI, cloudBlobClient);
var stream = cloudBlob.OpenRead();
return stream;
}
or create an instance of CloudBlockBlob using the Blob URI and Storage Credentials by doing something like:
public static Stream GetBlobAsStream(Uri blobURI)
{
var storageAccount = CloudStorageAccount.Parse(AZURE_STORAGE_CONNECTION_STRING);
var cloudBlob = new CloudBlockBlob(blobURI, storageAccount.Credentials);
var stream = cloudBlob.OpenRead();
return stream;
}
I am new to working with azure via C# and I am looking to upload an existing file to an existing azure storage container. I am currently able to create a new local file and then upload it to a container that I create as seen in the CreateContainerAndUploadFile method. However when I try to upload an existing file to an existing container it does not work. When using the CreateContainerAndUploadFile method I see the new container and .txt file appear, but the UploadFile method runs all the way through with no errors and I do not see the file appear in the container.
If anyone knows why the method is running through but not uploading I would greatly appreciate the help.
public class Launcher
{
public static void Main(string[] args)
{
BlobManager manager = new BlobManager();
manager.UploadFile("DemoText.txt", "democontainer");
manager.CreateContainerAndUploadFile("demo");
}
}
public class BlobManager
{
private BlobServiceClient blobServiceClient;
public BlobManager()
{
try
{
// Get azure table storage connection string.
string connectionString = ConfigurationManager.AppSettings.Get("StorageConnectionString");
blobServiceClient = new BlobServiceClient(connectionString);
}
catch (Exception ExceptionObj)
{
throw ExceptionObj;
}
}
public void UploadFile(string fileName, string container)
{
Console.WriteLine("Entering Upload to existing blob");
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(container);
containerClient.CreateIfNotExistsAsync();
Console.WriteLine("Existing blob obtained");
string localPath = "./";
string localFilePath = Path.Combine(localPath, fileName);
Console.WriteLine("Local file path set");
CloudBlockBlob blockBlob;
//// Create a block blob
BlobClient blobClient = containerClient.GetBlobClient(fileName);
Console.WriteLine($"BlobClient established with filename {fileName}");
//// Open the file and upload its data
using FileStream uploadFileStream = File.OpenRead(localFilePath);
blobClient.UploadAsync(uploadFileStream, true);
uploadFileStream.Close();
Console.WriteLine("Uploaded File to existing container");
}
public void CreateContainerAndUploadFile(string containerName)
{
//Create a BlobServiceClient object which will be used to create a container client
BlobServiceClient blobServiceClient =
new BlobServiceClient(ConfigurationManager.AppSettings.Get("StorageConnectionString"));
Console.WriteLine("Pre-container");
// Create the container and return a container client object
BlobContainerClient containerClient = blobServiceClient.CreateBlobContainer(containerName + Guid.NewGuid());
Console.WriteLine("Post-container");
// Create a local file in the ./data/ directory for uploading and downloading
string localPath = "./";
string fileName = "demo" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, fileName);
// Write text to the file
File.WriteAllTextAsync(localFilePath, "Hello, World!");
// Get a reference to the blob
BlobClient blobClient = containerClient.GetBlobClient(fileName);
Console.WriteLine($"Uploading to Blob storage as blob: {fileName}");
//// Open the file and upload its data
using FileStream uploadFileStream = File.OpenRead(localFilePath);
blobClient.UploadAsync(uploadFileStream, true);
uploadFileStream.Close();
}
}
The reason you're not able to upload the blob is because you're calling an async function but not waiting for it to complete.
Considering your calling method is sync and not async, I would recommend changing the following line of code:
blobClient.UploadAsync(uploadFileStream, true);
to
blobClient.Upload(uploadFileStream, true);
Other alternative would be to convert the wrapper method as async methods and await the completion of all async methods.
Is is possible to rename an Azure Storage Blob using the Azure Storage API from a Web Role? The only solution I have at the moment is to copy the blob to a new blob with the correct name and delete the old one.
UPDATE:
I updated the code after #IsaacAbrahams comments and #Viggity's answer, this version should prevent you from having to load everything into a MemoryStream, and waits until the copy is completed before deleting the source blob.
For anyone getting late to the party but stumbling on this post using Azure Storage API V2, here's an
extension method to do it quick and dirty (+ async version):
public static class BlobContainerExtensions
{
public static void Rename(this CloudBlobContainer container, string oldName, string newName)
{
//Warning: this Wait() is bad practice and can cause deadlock issues when used from ASP.NET applications
RenameAsync(container, oldName, newName).Wait();
}
public static async Task RenameAsync(this CloudBlobContainer container, string oldName, string newName)
{
var source = await container.GetBlobReferenceFromServerAsync(oldName);
var target = container.GetBlockBlobReference(newName);
await target.StartCopyFromBlobAsync(source.Uri);
while (target.CopyState.Status == CopyStatus.Pending)
await Task.Delay(100);
if (target.CopyState.Status != CopyStatus.Success)
throw new Exception("Rename failed: " + target.CopyState.Status);
await source.DeleteAsync();
}
}
Update for Azure Storage 7.0
public static async Task RenameAsync(this CloudBlobContainer container, string oldName, string newName)
{
CloudBlockBlob source =(CloudBlockBlob)await container.GetBlobReferenceFromServerAsync(oldName);
CloudBlockBlob target = container.GetBlockBlobReference(newName);
await target.StartCopyAsync(source);
while (target.CopyState.Status == CopyStatus.Pending)
await Task.Delay(100);
if (target.CopyState.Status != CopyStatus.Success)
throw new Exception("Rename failed: " + target.CopyState.Status);
await source.DeleteAsync();
}
Disclaimer: This is a quick and dirty method to make the rename execute in a synchronous way. It fits my purposes, however as other users noted, copying can take a long time (up to days), so the best way is NOT to perform this in 1 method like this answer but instead:
Start the copy process
Poll the status of the copy operation
Delete the original blob when the copy is completed.
There is practical way to do so, although Azure Blob Service API does not directly support ability to rename or move blobs.
You can, however, copy and then delete.
I originally used code from #Zidad, and in low load circumstances it usually worked (I'm almost always renaming small files, ~10kb).
DO NOT StartCopyFromBlob then Delete!!!!!!!!!!!!!!
In a high load scenario, I LOST ~20% of the files I was renaming (thousands of files). As mentioned in the comments on his answer, StartCopyFromBlob just starts the copy. There is no way for you to wait for the copy to finish.
The only way for you to guarantee the copy finishes is to download it and re-upload. Here is my updated code:
public void Rename(string containerName, string oldFilename, string newFilename)
{
var oldBlob = GetBlobReference(containerName, oldFilename);
var newBlob = GetBlobReference(containerName, newFilename);
using (var stream = new MemoryStream())
{
oldBlob.DownloadToStream(stream);
stream.Seek(0, SeekOrigin.Begin);
newBlob.UploadFromStream(stream);
//copy metadata here if you need it too
oldBlob.Delete();
}
}
While this is an old post, perhaps this excellent blog post will show others how to very quickly rename blobs that have been uploaded.
Here are the highlights:
//set the azure container
string blobContainer = "myContainer";
//azure connection string
string dataCenterSettingKey = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", "xxxx",
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
//setup the container object
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(dataCenterSettingKey);
CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(blobContainer);
// Set permissions on the container.
BlobContainerPermissions permissions = new BlobContainerPermissions();
permissions.PublicAccess = BlobContainerPublicAccessType.Blob;
container.SetPermissions(permissions);
//grab the blob
CloudBlob existBlob = container.GetBlobReference("myBlobName");
CloudBlob newBlob = container.GetBlobReference("myNewBlobName");
//create a new blob
newBlob.CopyFromBlob(existBlob);
//delete the old
existBlob.Delete();
Copy the blob, then delete it.
Tested for files of 1G size, and it works OK.
For more information, see the sample on MSDN.
StorageCredentials cred = new StorageCredentials("[Your?storage?account?name]", "[Your?storage?account?key]");
CloudBlobContainer container = new CloudBlobContainer(new Uri("http://[Your?storage?account?name].blob.core.windows.net/[Your container name] /"), cred);
string fileName = "OldFileName";
string newFileName = "NewFileName";
await container.CreateIfNotExistsAsync();
CloudBlockBlob blobCopy = container.GetBlockBlobReference(newFileName);
if (!await blobCopy.ExistsAsync())
{
CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
if (await blob.ExistsAsync())
{
// copy
await blobCopy.StartCopyAsync(blob);
// then delete
await blob.DeleteIfExistsAsync();
}
}
Renaming is not possible. Here is a workaround using Azure SDK for .NET v12:
BlobClient sourceBlob = container.GetBlobClient(sourceBlobName);
BlobClient destBlob = container.GetBlobClient(destBlobName);
CopyFromUriOperation ops = await destBlob.StartCopyFromUriAsync(sourceBlob.Uri);
long copiedContentLength = 0;
while (ops.HasCompleted == false)
{
copiedContentLength = await ops.WaitForCompletionAsync();
await Task.Delay(100);
}
await sourceBlob.DeleteAsync();
You can now with the new release in public preview of ADLS Gen 2 ( Azure Data Lake Storage Gen 2)
The Hierarchical Namespace capability allows you to perform atomic manipulation of directories and files which includes Rename operation.
However, make note of the following:
"With the preview release, if you enable the hierarchical namespace, there is no interoperability of data or operations between Blob and Data Lake Storage Gen2 REST APIs. This functionality will be added during preview."
You will need to make sure you create the blobs (files ) using ADLS Gen 2 to rename them. Otherwise, wait for the interoperability between Blob APIs and ADLS Gen 2 to be added during the preview time period.
Using Monza Cloud's Azure Explorer, I can rename an 18 Gigabyte blob in under a second. Microsoft's Azure Storage Explorer takes 29 sec to clone that same blob, so Monza is not
doing a copy. I know it is fast because immediately after the Monza rename, clicking the container in Microsoft Azure Storage Explorer shows the blob with the new name.
The only way at the mement is to move the src blob to a new destination/name. Here is my code to do this
public async Task<CloudBlockBlob> RenameAsync(CloudBlockBlob srcBlob, CloudBlobContainer destContainer,string name)
{
CloudBlockBlob destBlob;
if (srcBlob == null && srcBlob.Exists())
{
throw new Exception("Source blob cannot be null and should exist.");
}
if (!destContainer.Exists())
{
throw new Exception("Destination container does not exist.");
}
//Copy source blob to destination container
destBlob = destContainer.GetBlockBlobReference(name);
await destBlob.StartCopyAsync(srcBlob);
//remove source blob after copy is done.
srcBlob.Delete();
return destBlob;
}
Here is a code sample if you want the blob lookup as part of the method:
public CloudBlockBlob RenameBlob(string oldName, string newName, CloudBlobContainer container)
{
if (!container.Exists())
{
throw new Exception("Destination container does not exist.");
}
//Get blob reference
CloudBlockBlob sourceBlob = container.GetBlockBlobReference(oldName);
if (sourceBlob == null && sourceBlob.Exists())
{
throw new Exception("Source blob cannot be null and should exist.");
}
// Get blob reference to which the new blob must be copied
CloudBlockBlob destBlob = container.GetBlockBlobReference(newName);
destBlob.StartCopyAsync(sourceBlob);
//Delete source blob
sourceBlob.Delete();
return destBlob;
}
There is also a way without copying your blob to rename it, and without running any script: mounting Azure Blob storage to your OS: https://learn.microsoft.com/bs-latn-ba/azure/storage/blobs/storage-how-to-mount-container-linux
Then you can just use mv and your blob will be renamed instantly.
Using Azure Storage Explorer is the easiest way to manually rename a blob. You can download it here https://azure.microsoft.com/en-us/features/storage-explorer/#overview
If you set the ContentDisposition property with
attachment;filename="yourfile.txt"
The name of the download over http will be whatever you want.
I think Storage was built with the assumption that data would be stored in a way with unique identifiers primarily used as the filenames. Issuing Shared Access Signatures for all downloads is a bit weird though, so this isn't ideal for some people.
But I think abstracting away the user-facing filename is overall a good practice and encourages a more stable architecture overall.
This worked for me in live environment of 100K Users having file sizes no more than 100 mb. This is similar synchronous approach to #viggity's answer. But the difference is that its copying everything on Azure side so you don't have to hold Memorystream on your server for Copy/Upload to new Blob.
var account = new CloudStorageAccount(new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(StorageAccountName, StorageAccountKey), true);
CloudBlobClient blobStorage = account.CreateCloudBlobClient();
CloudBlobContainer container = blobStorage.GetContainerReference("myBlobContainer");
string fileName = "OldFileName";
string newFileName = "NewFileName";
CloudBlockBlob oldBlob = container.GetBlockBlobReference(fileName);
CloudBlockBlob newBlob = container.GetBlockBlobReference(newFileName);
using (var stream = new MemoryStream())
{
newBlob.StartCopyFromBlob(oldBlob);
do { } while (!newBlob.Exists());
oldBlob.Delete();
}