Last active
August 24, 2020 12:46
-
-
Save LauraKokkarinen/c272a87dd9e12dd4895ef4221ba7e559 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Threading.Tasks; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.WindowsAzure.Storage; | |
using Microsoft.WindowsAzure.Storage.Blob; | |
namespace AzureFunctionsDependencyInjection.Services | |
{ | |
public class BlobService : IBlobService | |
{ | |
private readonly CloudBlobContainer _container; | |
public BlobService(IConfiguration configuration) | |
{ | |
_container = GetContainer(configuration["StorageAccountConnectionString"], configuration["BlobContainerName"]); | |
} | |
private CloudBlobContainer GetContainer(string storageAccountConnectionString, string blobContainerNAme) | |
{ | |
try | |
{ | |
var storageAccount = CloudStorageAccount.Parse(storageAccountConnectionString); | |
var blobClient = storageAccount.CreateCloudBlobClient(); | |
return blobClient.GetContainerReference(blobContainerNAme); | |
} | |
catch (Exception e) | |
{ | |
throw new Exception($"Failed to retrieve blob container by name '{blobContainerNAme}'. {e.Message}"); | |
} | |
} | |
public async Task<string> GetBlobContentAsync(string blobName) | |
{ | |
var blob = _container.GetBlobReference(blobName); | |
if (await blob.ExistsAsync() == false) return null; | |
string content; | |
using (var memoryStream = new MemoryStream()) | |
{ | |
await blob.DownloadToStreamAsync(memoryStream); | |
memoryStream.Seek(0, SeekOrigin.Begin); | |
using (var streamReader = new StreamReader(memoryStream)) | |
{ | |
content = streamReader.ReadToEnd(); | |
} | |
} | |
return content; | |
} | |
public async Task SetBlobContentAsync(string blobName, string content) | |
{ | |
var blobReference = _container.GetAppendBlobReference(blobName); | |
await blobReference.UploadTextAsync(content); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment