forked from FBoucher/AzUnzipEverything
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUnzipthis.cs
65 lines (59 loc) · 2.8 KB
/
Unzipthis.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
namespace AzUnzipEverything
{
public static class Unzipthis
{
[FunctionName("Unzipthis")]
public static async Task Run(
[BlobTrigger("input-files/{name}", Connection = "cloud5mins_storage")]CloudBlockBlob blob,
string name,
ILogger log)
{
log.LogInformation($"C# Blob trigger function Processed blob Name: {name}");
// Exit if not a zip file
if(name.Split('.').Last().ToLower() != "zip")
{
log.LogError($"{name} is not a zip file");
return;
}
var destinationStorage = Environment.GetEnvironmentVariable("destinationStorage");
var destinationContainer = Environment.GetEnvironmentVariable("destinationContainer");
try
{
var storageAccount = CloudStorageAccount.Parse(destinationStorage);
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference(destinationContainer);
using(var sourceStream = await blob.OpenReadAsync())
{
using(var zipArchive = new ZipArchive(sourceStream))
{
foreach(var zipArchiveEntry in zipArchive.Entries)
{
//Replace all NO digits, letters, or "-" by a "-" Azure storage is specific on valid characters
var targetFileName = Regex.Replace(zipArchiveEntry.Name, @"[^a-zA-Z0-9\-.]","-").ToLower();
var targetBlob = container.GetBlockBlobReference(targetFileName);
using(var sourceFileStream = zipArchiveEntry.Open())
{
log.LogInformation($"started extracting {zipArchiveEntry.Name} ({zipArchiveEntry.CompressedLength}) to {targetFileName} ({zipArchiveEntry.Length})");
await targetBlob.UploadFromStreamAsync(sourceFileStream);
log.LogInformation($"completed extracting {zipArchiveEntry.Name} to {targetFileName}");
}
}
}
}
}
catch(Exception ex){
log.LogError(ex, ex.Message);
}
}
}
}