Azure Blob存储:使用C#从Azure存储容器“ $ logs”下载所有日志

时间:2020-06-23 12:37:04

标签: azure azure-storage azure-storage-blobs

我正在尝试从容器“ $ logs ”下载所有日志,但是它始终会引发异常-

“找不到路径'C:\ logs \ blob \ 2020 \ 05 \ 24 \ 2300 \ 000000.log'的一部分”

public static void GetAnalyticsLogs(CloudBlobClient blobClient, CloudTableClient tableClient)
{
    try
    {
        DateTime time = DateTime.UtcNow;
        CloudAnalyticsClient analyticsClient = new CloudAnalyticsClient(blobClient.StorageUri, tableClient.StorageUri, tableClient.Credentials);
        IEnumerable<ICloudBlob> results = analyticsClient.ListLogs(StorageService.Blob, time.AddDays(-30), null, LoggingOperations.All, BlobListingDetails.Metadata, null, null);
        List<ICloudBlob> logs = results.ToList();
        foreach (var item in logs)
        {
            string name = ((CloudBlockBlob)item).Name;
            CloudBlobContainer container = blobClient.GetContainerReference("$logs");
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(name);
            string path = (@"C:/logs/" + name);
            using (var fileStream = System.IO.File.Create(path))
            {
                blockBlob.DownloadToStream(fileStream);
            }
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
}

我们如何解决此错误?

1 个答案:

答案 0 :(得分:0)

原因是该路径包含目录,但是如果该目录不存在,则File.Create()方法无法在目录内创建文件。因此,您应该首先创建目录,然后使用File.Create()方法创建文件。

下面的代码在我这边工作正常:

public static void GetAnalyticsLogs(CloudBlobClient blobClient, CloudTableClient tableClient)
{
    try
    {
        DateTime time = DateTime.UtcNow;
        CloudAnalyticsClient analyticsClient = new CloudAnalyticsClient(blobClient.StorageUri, tableClient.StorageUri, tableClient.Credentials);
        IEnumerable<ICloudBlob> results = analyticsClient.ListLogs(StorageService.Blob, time.AddDays(-30), null, LoggingOperations.All, BlobListingDetails.Metadata, null, null);
        List<ICloudBlob> logs = results.ToList();
        foreach (var item in logs)
        {
            string name = ((CloudBlockBlob)item).Name;
            CloudBlobContainer container = blobClient.GetContainerReference("$logs");
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(name);

            //specify the directory without file name
            string sub_folder = name.Remove(name.LastIndexOf("/") + 1);                   
            string path = (@"C:/logs/" + sub_folder);

            //create the directory if it does not exist.
            Directory.CreateDirectory(path);

            //specify the file full path
            string file_path= (@"C:/logs/" + name);

            using (var fileStream = File.Create(file_path))
            {
                
                blockBlob.DownloadToStream(fileStream);
            }
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
}