我想将azure中容器中的所有文件下载为zip文件,并使下载路径成为动态 这是现在的代码
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
string[] arr = userName.Split('\\');
string path = $@"C:\Users\{arr[1]}\Downloads\";
CloudBlobContainer contianner = BlobClient.GetContainerReference(contianerName);
var list = contianner.ListBlobs();
/// Console.WriteLine(list.Count());
string[] FilesName = new string[list.Count()];
int i = 0;
foreach (var blob in list)
{
string[] Name = blob.Uri.AbsolutePath.Split('/');
FilesName[i++] = Name[2];
// Console.WriteLine(Name[2]);
CloudBlockBlob blockBlob = contianner.GetBlockBlobReference(Name[2]);
System.IO.Directory.CreateDirectory($@"{path}ImagesPath");
using (var fileStream = System.IO.File.OpenWrite($@"{path}\ImagesPath\{Name[2]}"))
{
blockBlob.DownloadToStream(fileStream);
}
}
答案 0 :(得分:0)
您需要使用3个步骤完成工作。
步骤1,将所有文件下载到文件夹。我建议您在Web应用程序的内容文件夹下创建一个文件夹。
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("storage connection string");
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
string containerName = "mycontainer";
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference(containerName);
var blobs = container.ListBlobs(string.Empty, true);
string currentDateTime = DateTime.Now.ToString("yyyyMMddhhmmss");
string directoryPath = Server.MapPath("~/Content/" + containerName + currentDateTime);
System.IO.Directory.CreateDirectory(directoryPath);
foreach (CloudBlockBlob blockBlob in blobs)
{
string[] segements = blockBlob.Name.Split('/');
string subFolderPath = directoryPath;
for (int i = 0; i < segements.Length - 1; i++)
{
subFolderPath = subFolderPath + "\\" + segements[i];
if (!System.IO.Directory.Exists(subFolderPath))
{
System.IO.Directory.CreateDirectory(subFolderPath);
}
}
string filePath = directoryPath + "\\" + blockBlob.Name;
blockBlob.DownloadToFile(filePath, System.IO.FileMode.CreateNew);
}
Console.WriteLine("Download files successful.");
步骤2,下载文件后,我们可以使用System.IO.Compression.ZipFile类压缩文件夹。要使用它,我们需要添加对2个程序集的引用。 System.IO.Compression和System.IO.Compression.FileSystem。
System.IO.Compression.ZipFile.CreateFromDirectory(directoryPath, directoryPath + ".zip");
Console.WriteLine("Compress the folder successfully");
步骤3,由于zip文件是在内容文件夹中生成的,因此您可以生成用于下载操作的URL。
string url = "http://hostname:port/content/" + containerName + currentDateTime + ".zip";