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

Azure Blob Storage: Download all logs from Azure Storage Container "$logs" using C#

我正在尝试从容器“$logs”下载所有日志,但它总是抛出异常 -

“找不到部分路径 'C:\logs\blob2000[=21=]0000.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);
    }
}

我们如何解决这个错误?

原因是路径包含目录,但如果目录不存在,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);
    }
}