Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System.Collections.Generic;
using System.Threading.Tasks;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Microsoft.AspNetCore.Http;
namespace azblob.Services
{
public class BlobService : IBlobService
{
private readonly BlobServiceClient _blobClient;
public BlobService(BlobServiceClient blobClient)
{
_blobClient = blobClient;
}
public async Task<IEnumerable<string>> AllBlobs(string containerName)
{
// allow us to get access to data inside container
var containerClient = _blobClient.GetBlobContainerClient(containerName);
var files = new List<string>();
var blobs = containerClient.GetBlobsAsync();
await foreach (var item in blobs)
{
files.Add(item.Name);
}
return files;
}
public async Task<bool> DeleteBlob(string name, string containerName)
{
var containerClient = _blobClient.GetBlobContainerClient(containerName);
var blobClient = containerClient.GetBlobClient(name);
return await blobClient.DeleteIfExistsAsync();
}
public async Task<string> GetBlob(string name, string containerName)
{
var containerClient = _blobClient.GetBlobContainerClient(containerName);
var blobClient = containerClient.GetBlobClient(name);
return await Task.Run(() => blobClient.Uri.AbsoluteUri);
}
public async Task<bool> UploadBlob(string name, IFormFile file, string containerName)
{
var containerClient = _blobClient.GetBlobContainerClient(containerName);
// checking is current file is exit; if exit then ovverrite
var blobClient = containerClient.GetBlobClient(name);
var httpHeaders = new BlobHttpHeaders()
{
ContentType = file.ContentType
};
var res = await blobClient.UploadAsync(file.OpenReadStream(), httpHeaders);
if (res != null) return true;
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment