I am getting confused with the C# azure sdk.
What I am trying to achieve.
Upload files from my computer to a folder in azure.
For example
Locally
MyFiles
-- Folder1
-- file.txt
-- img.jpg
-- Folder2
-- file2.json
-- test.png
Azure Result
Container
MyFiles
-- Folder1
-- file.txt
-- img.jpg
-- Folder2
-- file2.json
-- test.png
So I want in my container on azure same file structure.
how I am doing it is
var sasCred = new AzureSasCrdentials("sasurl");
var container = new BlobContainerClient(new Uri("containerUrl"), sasCred);
var allFiles = Directory.GetFiles("MyFilesFolderPath", "*", SearchOption.AllDirectories);
foreach(var file in files)
{
var cloudFilePath = file.Replace("MyFilesFolderPath", string.Empty);
var fullPath= $"MyFiles{cloudFilePath};
using(var s = new MemoryStream(File.ReadAllBytes(file))
{
await container.UploadBlobAsync(fullPath,stream);
}
}
This seems to do what I need it to do though I noticed the file type is something like "file octet stream" instead of .json/.png/txt or whatever it should be.
When I search it talks about using BlobCLient to set the file type but now I am sure if I should be using BlobContainerClient or not.
CodePudding user response:
To set the content type of a blob in a container using the BlobContainerClient class in Azure Blob Storage, you can use the SetBlobProperties method and specify the ContentType property of the BlobHttpHeaders class as the desired content type.
There are also nuget libraries to get the mime type from the file name extension if they vary by upload.
BlobHttpHeaders headers = new BlobHttpHeaders
{
ContentType = "text/plain"
};
container.SetBlobProperties(blobName, headers: headers);
CodePudding user response:
You would need to use both BlobContainerClient
and BlobClient
in this case. The way you would do it is that you would create an instance of BlobClient
(BlockBlobClient
specifically) using BlobContainerClient
and blob name and use UploadAsync
method there.
Your code (untested) would be something like:
var sasCred = new AzureSasCrdentials("sasurl");
var container = new BlobContainerClient(new Uri("containerUrl"), sasCred);
var allFiles = Directory.GetFiles("MyFilesFolderPath", "*", SearchOption.AllDirectories);
foreach(var file in files)
{
var cloudFilePath = file.Replace("MyFilesFolderPath", string.Empty);
var fullPath= $"MyFiles{cloudFilePath};
using (var s = new MemoryStream(File.ReadAllBytes(file))
{
var blockBlob = container.GetBlockBlobClient(fullPath);//Get BlockBlobClient instance
var blobContentType = GetContentTypeFromFileSomehow(file);//Write a helper method to get the content type
var headers = new BlobHttpHeaders() { ContentType = blobContentType};//Set content type header for blob.
var blobUploadOptions = new BlobUploadOptions() { HttpHeaders = headers};
await blockBlob.UploadAsync(s, blobUploadOptions);//Upload blob
}
}