简体   繁体   中英

Uploading images to azure blob storage with c# issue

I wrote a little console app to upload files in a folder on my local machine to Azure blob storage and my issue is that the code compiles and runs without error BUT I do not get the expected result.

What I expect is for all the files in FolderPath to get uploaded to container and IF container doesn't exist to create it but it never gets created and the console is telling me everything is being uploaded. My expectations of my code are probably incorrect then.

using System;
using System.IO;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Blob.Protocol;

namespace AzureBlobs
{
    class Program
    {

        const string StorageAccountName = "cs72e88a177daeax40edxbf2";
        const string StorageAccountKey = "[ACCOUNT KEY]";
        const string FolderPath = @"[LOCAL FILE PATH]";

        static void Main()
        {
            var storageAccount = new CloudStorageAccount(new StorageCredentials(StorageAccountName, StorageAccountKey), true);

            var blobclient = storageAccount.CreateCloudBlobClient();

            var container = blobclient.GetContainerReference("newcontainer");

            container.CreateIfNotExistsAsync();

            container.SetPermissionsAsync(new BlobContainerPermissions()
            {
                PublicAccess = BlobContainerPublicAccessType.Blob
            });

            foreach( var filePath in Directory.GetFiles(FolderPath, "*.*", SearchOption.AllDirectories))
            {
                var blob = container.GetBlockBlobReference(filePath);
                blob.UploadFromFileAsync(filePath);

                Console.WriteLine("Uploaded {0}", filePath);
            }

            Console.WriteLine("Donzos!");
        }
    }
}

The issue is that most of the Azure SDK methods that you are calling are async but you are not awaiting them. So they are essentially all fire and forget .

I create a console app and things works on my side, you can have a check of your code(the package that I use is the Microsoft.Azure.Storage.Blob ),

using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Blob;
using System;
using System.IO;

namespace uploadFilesToStorage
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Lets start upload files to Azure Storage!");

            string folderpath = @"C:\Users\bowmanzh\Pictures\images";
            var storageAccount = CloudStorageAccount
                .Parse("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
            var myClient = storageAccount.CreateCloudBlobClient();
            var container = myClient.GetContainerReference("case");
            foreach (var filepath in Directory.GetFiles(folderpath,"*.*",SearchOption.AllDirectories)) {
                var blockBlob = container.GetBlockBlobReference(filepath);
                blockBlob.UploadFromFileAsync(filepath);
            }

            Console.ReadLine();
        }
    }
}

在此处输入图像描述

note:

WindowsAzure.Storage (latest is v9.3.2) is the legacy Storage SDK we always use and Microsoft.Azure.Storage.* (latest v11.1.0) is its new release.

Check the changelog of Storage .NET SDK. List part of those important differences/changes.

Microsoft.Azure.Storage splits libraries to three parts, Blob, Queue and File, which means we can install separate package instead of the full edition.

Microsoft.Azure.Storage doesn't support Table API, it is transferred to Microsoft.Azure.Cosmos.Table .

Microsoft.Azure.Storage added NetStandard2.0 target support since 9.4.0-preview, which supports synchronous methods wrapped over the asynchronous APIs. WindowsAzure.Storage on NetStandard only has asynchronous APIs.

You are using the API incorrectly. You have to await all the API methods that return Task . First step is to make your Main method async (this is a C# 7.1 feature).

static async Task Main()

(To use Task you also need to add using System.Threading.Tasks; at the top of your source file.)

Next you need to await all the asynchronous methods:

container.CreateIfNotExistsAsync();

becomes

await container.CreateIfNotExistsAsync();

This means that your code will only continue executing after the container has been created. Without the await your code will send the API request to Azure but immediately continue to execute without waiting for Azure to complete the request.

You also have to await container.SetPermissionsAsync and blob.UploadFromFileAsync . However, if you forget to await an async method in another async method ( Main in your case) you get a compiler warning so you should notice if you make any mistakes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM