I'm using Azure Storage to store files for my .NET Core app. And I need possibility to save temp files.
I'm uploading file this way:
public async Task UploadFile(Stream fileStream, string path)
{
var connectionString = "connection string";
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
BlobContainerClient blobContainerClient =
blobServiceClient.GetBlobContainerClient("files");
BlobClient blobClient = blobContainerClient.GetBlobClient(path);
fileStream.Position = 0;
BlobUploadOptions uploadOptions = new BlobUploadOptions();
var extension = path.Split(".").LastOrDefault();
if (!string.IsNullOrEmpty(extension) && MimeTypes.Values.ContainsKey(extension))
{
var contentType = MimeTypes.Values[extension];
var blobHttpHeader = new BlobHttpHeaders { ContentType = contentType };
uploadOptions.HttpHeaders = blobHttpHeader;
}
await blobClient.UploadAsync(fileStream, uploadOptions);
}
Is there way to create file that will be deleted automatically in an hour for example?
UPDATED CODE
var connectionString = "connection string";
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
BlobContainerClient blobContainerClient =
blobServiceClient.GetBlobContainerClient("files");
BlobClient blobClient = blobContainerClient.GetBlobClient(path);
fileStream.Position = 0;
BlobUploadOptions uploadOptions = new BlobUploadOptions();
var extension = path.Split(".").LastOrDefault();
if (!string.IsNullOrEmpty(extension) && MimeTypes.Values.ContainsKey(extension))
{
var contentType = MimeTypes.Values[extension];
var blobHttpHeader = new BlobHttpHeaders { ContentType = contentType };
uploadOptions.HttpHeaders = blobHttpHeader;
}
await blobClient.UploadAsync(fileStream, uploadOptions);
if (expiration)
{
var blobSasBuilder = new BlobSasBuilder
{
StartsOn = DateTime.UtcNow,
ExpiresOn = DateTime.UtcNow.AddMinutes(5),
BlobContainerName = blobClient.BlobContainerName,
BlobName = blobClient.Name
};
blobSasBuilder.SetPermissions(BlobSasPermissions.Read);
StorageSharedKeyCredential storageSharedKeyCredential;
var csBuilder = new DbConnectionStringBuilder();
csBuilder.ConnectionString = connectionString;
storageSharedKeyCredential = new StorageSharedKeyCredential((string)csBuilder["AccountName"], (string)csBuilder["AccountKey"]);
BlobSasQueryParameters sasQueryParameters = blobSasBuilder.ToSasQueryParameters(storageSharedKeyCredential);
string url;
url = blobClient.Uri.AbsoluteUri.Replace("%2F", "/").ToString() + "?comp=expiry&" + sasQueryParameters.ToString();
using (HttpClient httpClient = new HttpClient())
{
// Set the Expiry Time
HttpRequestMessage expiryRequest = new HttpRequestMessage(HttpMethod.Put, url);
expiryRequest.Headers.Add("x-ms-version", "2020-02-10");
expiryRequest.Headers.Add("x-ms-expiry-time", "300000"); // 5 minutes
expiryRequest.Headers.Add("x-ms-expiry-option", "RelativeToNow");
expiryRequest.Headers.Add("x-ms-date", DateTime.UtcNow.ToString("R"));
HttpResponseMessage expiryResponse = await httpClient.SendAsync(expiryRequest);
if (!expiryResponse.IsSuccessStatusCode)
{
Console.WriteLine($"Error setting expiry: {expiryResponse.StatusCode} - {await expiryResponse.Content.ReadAsStringAsync()}");
}
}
}
Is there way to create file that will be deleted automatically in an hour for example?
You can use the below code to upload the blob and set the expiration date of a blob relative to the current time with the request
method in the Azure storage using C#.
Code:
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string url = "https://<storage account name>.blob.core.windows.net";
string containerName = "<container name>";
string blobName = "<blob>";
string SAStoken = "<Sas token>";
DateTime dt = DateTime.UtcNow;
// The file you want to upload
string filePath = @"C:\Downloads\test.png";
using (HttpClient httpClient = new HttpClient())
{
// Upload the Blob
HttpRequestMessage uploadRequest = new HttpRequestMessage(HttpMethod.Put, new Uri($"{ url}/{containerName}/{blobName}?{SAStoken}"));
byte[] fileBytes = await File.ReadAllBytesAsync(filePath);
uploadRequest.Content = new ByteArrayContent(fileBytes);
uploadRequest.Headers.Add("x-ms-blob-type", "BlockBlob");
HttpResponseMessage uploadResponse = await httpClient.SendAsync(uploadRequest);
if (uploadResponse.IsSuccessStatusCode)
{
Console.WriteLine("Blob uploaded successfully");
// Set the Expiry Time
HttpRequestMessage expiryRequest = new HttpRequestMessage(HttpMethod.Put, new Uri($"{url}/{containerName}/{blobName}?comp=expiry&{SAStoken}"));
expiryRequest.Headers.Add("x-ms-version", "2020-02-10");
expiryRequest.Headers.Add("x-ms-expiry-time", "3600000"); // one hour
expiryRequest.Headers.Add("x-ms-expiry-option", "RelativeToNow");
expiryRequest.Headers.Add("x-ms-date", dt.ToString("R"));
HttpResponseMessage expiryResponse = await httpClient.SendAsync(expiryRequest);
if (expiryResponse.IsSuccessStatusCode)
{
Console.WriteLine("Expiry time added to the blob successfully");
}
else
{
Console.WriteLine($"Error setting expiry: {expiryResponse.StatusCode} - {await expiryResponse.Content.ReadAsStringAsync()}");
}
}
else
{
Console.WriteLine($"Error uploading blob: {uploadResponse.StatusCode} - {await uploadResponse.Content.ReadAsStringAsync()}");
}
}
}
}
Output:
Blob uploaded successfully
Expiry time added to the blob successfully
The above code operation is allowed only on hierarchical namespace
enabled storage accounts.
Reference: Set Blob Expiry (REST API) - Azure Storage | Microsoft Learn