'Uploading the file on azure blob container doesn't work
I am trying to upload a file on an azure blob, the purpose of this application is to log all the exceptions to the azure blob, for this purpose I created a .net core console application and called this application using web API but it runs perfectly fine from the local system, but when I upload/deploy it on azure app service it doesn't work at all, your help would be highly appreciated. thank you :-)
public static async Task UploadBlob(string Information)
{
var connectionString = "ConnectionString Goes here";
string containerName = "logs";
var serviceClient = new BlobServiceClient(connectionString);
var containerClient = serviceClient.GetBlobContainerClient(containerName);
var path = @"c:\temp";
var fileName = "filename.txt";
var localFile = Path.Combine(path, fileName);
await File.WriteAllTextAsync(localFile, Information);
var blobClient = containerClient.GetBlobClient($"{DateTime.Now.Year}/{DateTime.Now.Month}/{DateTime.Now.Day}/{fileName}");
//var blobClient = containerClient.GetBlobClient(sal/fileName);
Console.WriteLine("Uploading to Blob storage");
using FileStream uploadFileStream = File.OpenRead(localFile);
await blobClient.UploadAsync(uploadFileStream, true);
uploadFileStream.Close();
}
Solution 1:[1]
You can use the below code to upload file to azure blob storage using c#:
public interface IStorage
{
Task Create(Stream stream, string path);
}
public class AzureBlobStorage : IStorage
{
public async Task Create(Stream stream, string path)
{
// Initialise client in a different place if you like
string storageConnectionString = "DefaultEndpointsProtocol=https;"
+ "AccountName=[ACCOUNT]"
+ ";AccountKey=[KEY]"
+ ";EndpointSuffix=core.windows.net";
CloudStorageAccount account = CloudStorageAccount.Parse(storageConnectionString);
var blobClient = account.CreateCloudBlobClient();
// Make sure container is there
var blobContainer = blobClient.GetContainerReference("test");
await blobContainer.CreateIfNotExistsAsync();
CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(path);
await blockBlob.UploadFromStreamAsync(stream);
}
}
class Program
{
static void Main(string[] args)
{
// Put your DI here
var storage = new AzureBlobStorage();
// Read a local file
using (FileStream file = File.Open(@"C:\cartoon.PNG", FileMode.Open))
{
try
{
// Pattern to run an async code from a sync method
storage.Create(file, "1.png").ContinueWith(t =>
{
if (t.IsCompletedSuccessfully)
{
Console.Out.WriteLine("Blob uploaded");
}
}).Wait();
}
catch (Exception e)
{
// Omitted
}
}
}
}
Reference: Azure Storage client libraries for .NET - Azure for .NET Developers
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RajkumarMamidiChettu-MT |
