写入 Azure 中的 blob

Writing to a blob In Azure

我有以下指向 .Net Core 2.1 的控制台应用程序,它执行从 blob 读取和写入的简单操作。 我用 * here.But 隐藏了帐户密钥,连接正常进行。

using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Blob;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
           
string connectionString = $"DefaultEndpointsProtocol=https;AccountName=r53eripcjroswtest;AccountKey=***;";

                // Setup the connection to the storage accounts
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

                // Connect to the blob storage
                CloudBlobClient serviceClient = storageAccount.CreateCloudBlobClient();

                // Connect to the blob container
                CloudBlobContainer container = serviceClient.GetContainerReference("igb-test");             
               

                CloudBlockBlob blob = container.GetBlockBlobReference("Test.txt");
                string contents = blob.DownloadTextAsync().Result;

                //blob.UploadTextAsync("This is coming from the Program");
           
            
        }
    }
}

我有 运行 上面的代码并且能够读取“contents”变量中的文件内容。 但是当我试图写入文件时(在取消注释 ---blob.UploadTextAsync("This is coming from the Program")-- 行并注释读取行之后),没有任何内容被写入文件。

注意:文本文件一开始是空的。首先我尝试通过我的控制台程序写入文件,没有任何反应然后打开文件并手动写入并能够读取其内容。

当我尝试通过 azure 函数 运行 相同的代码并将其发布到 azure 门户时,它能够读取和写入 from/to 文件。

我的问题是我们不能使用 .exe(控制台应用程序)写入 Azure 中的 Blob?并且只能通过功能应用程序才能完成? 谁能指导我哪里出了问题。

因为 UploadTextAsync 是一个异步方法,您将不得不等待它完成(就像您在下载中所做的那样)。请尝试以下代码:

blob.UploadTextAsync("This is coming from the Program").Result;

或者您可以简单地使用该方法的同步版本:

blob.UploadText("This is coming from the Program");

这是因为您正在使用 Async 进行操作。如果你用 Async 做,那么你需要这样做。

using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Blob;
using System;
using System.Threading.Tasks;

namespace WriteToBlob
{
    class Program
    {
        static void Main(string[] args)
        {

            var writeTask = WriteToBlobAsync("hello world 123");
            writeTask.Wait();
        }

        public static async Task WriteToBlobAsync(string text) {

            string connectionString = "*";

            // Setup the connection to the storage accounts
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            // Connect to the blob storage
            CloudBlobClient serviceClient = storageAccount.CreateCloudBlobClient();

            // Connect to the blob container
            CloudBlobContainer container = serviceClient.GetContainerReference("test");


            CloudBlockBlob blob = container.GetBlockBlobReference("test.txt");
            string contents = blob.DownloadTextAsync().Result;
            Console.WriteLine(contents);
            await blob.UploadTextAsync(text);


        }
    }
}