C#代码中的存储容器访问级别问题

时间:2020-07-27 06:46:40

标签: azure

我在存储帐户中有一个容器,并且我更改了它的配置允许Blob公共访问 禁用。我正在使用该容器的连接字符串来打开文件。当执行此行Stream Stream = await blob.OpenReadAsync()时,它将引发错误,表明不允许对此存储帐户进行公共访问。

即使我尝试使用SAS令牌代替连接字符串,也遇到同样的问题。

我希望我的“允许Blob公共访问”配置被禁用,并且需要使用我的代码c#来访问它。

        var storageConnection = configuration["STORAGE_CONNECTION"];
        var storageContainer = Configuration["StorageContainer"]; 
        CloudStorageAccount storageAccount = 
         CloudStorageAccount.Parse(storageConnection);
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = blobClient.GetContainerReference(storageContainer);

        var fileName = file.FileName;
        Console.WriteLine($"Procesing file: {fileName}");

        CloudBlob blob = new CloudBlob(new Uri(fileName));

        var lines = new List<string>();
        
        using (Stream stream = await blob.OpenReadAsync())
        {
            using (StreamReader reader = new StreamReader(stream))
            {
                string headerLine = reader.ReadLine();
                while (!reader.EndOfStream)
                {
                    var bodyLine = reader.ReadLine();
                    lines.Add(bodyLine);
                }
            }
        }

1 个答案:

答案 0 :(得分:0)

进行一些较小的更改就可以了。

public static async Task ReadToBlobAsync()
{
    var storageConnection = "DefaultEndpointsProtocol=https;AccountName=xxxxx;AccountKey=xxxxx;EndpointSuffix=core.windows.net";
    var storageContainer = "xxxx";
    CloudStorageAccount storageAccount =
    CloudStorageAccount.Parse(storageConnection);
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobClient.GetContainerReference(storageContainer);

    var fileName = "test.txt";
    Console.WriteLine($"Procesing file: {fileName}");

    CloudBlockBlob blob = container.GetBlockBlobReference("testcsv.csv");

    var lines = new List<string>();

    using (Stream stream = await blob.OpenReadAsync())
    {
        using (StreamReader reader = new StreamReader(stream))
        {
            string headerLine = reader.ReadLine();
            while (!reader.EndOfStream)
            {
                var bodyLine = reader.ReadLine();
                lines.Add(bodyLine);
            }
        }
    }
}