user12625850
user12625850

Reputation:

How to upload file to blob container?

I am trying to learn how to use blobs. With this code I want to upload my text file. I do not get errors. All that hapens is that the file is not found in the container. And I have read previous similar questions but none used this method.

What am I missing here?

using Azure.Storage.Blobs;
using System.IO;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Upload_it_Async();
        }

        private static async void Upload_it_Async()
        {

        var filepath = @"C:\my_file.txt";
        var connectionString = ***********;
        var containerName = "my_container";

        BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
        var container = blobServiceClient.GetBlobContainerClient(containerName);
        var blockBlob = container.GetBlobClient("my_file.txt");
        using (FileStream fs = File.Open(filepath, FileMode.Open))
        {
            await blockBlob.UploadAsync(fs);
        }
    }
}
}

Upvotes: 1

Views: 513

Answers (2)

JUstLearning
JUstLearning

Reputation: 25

Suggest use below code snippet.

static async Task Main(string[] args)
{
  await Upload_it_Async();
}

private static async Task Upload_it_Async()

And here are two good Azure StorageBlob Samples you can take a reference. And if you have any questions about Azure Storage, please be free let me know.

sample1

sample2

Upvotes: -1

Oliver
Oliver

Reputation: 9002

It looks like you need to wait for that task to complete:

static void Main(string[] args)
{
    Upload_it_Async().Wait();
}

//Change the method to Task, not void:
private static async Task Upload_it_Async()
...

See this link for more discussion around async usage in console applications.

As noted in the comments, doing this will ensure any exceptions are thrown in your Main method.

Upvotes: 2

Related Questions