【问题标题】:Azure storage not finding csv fileAzure 存储未找到 csv 文件
【发布时间】:2019-04-21 20:18:12
【问题描述】:

我正在尝试从我的 azure 存储帐户中读取 csv 文件。 将每一行转换为一个对象并构建这些对象的列表。 它总是出错,原因是它找不到文件(找不到 Blob)。该文件在那里,它是一个csv文件。

错误:

StorageException:指定的 blob 不存在。 AzureFileMethods.cs 中的 BatlGroup.Site.Services.AzureStorageService.AzureFileMethods.ReadCsvFileFromBlobAsync(CloudBlobContainer container, string fileName) + 等待 blob.DownloadToStreamAsync(memoryStream);

 public async Task<Stream> ReadCsvFileFromBlobAsync(CloudBlobContainer container, string fileName)
    {
        // Retrieve reference to a blob (fileName)
        var blob = container.GetBlockBlobReference(fileName);

        using (var memoryStream = new MemoryStream())
        {
            //downloads blob's content to a stream
             await blob.DownloadToStreamAsync(memoryStream);
            return memoryStream;

        }

    }

我已确定该文件是公开的。我可以下载存储在那里的任何文本文件,但没有 csv 文件。

我也不确定要采用什么格式,因为我需要遍历这些行。

我看到了将整个文件放到临时驱动器并在那里使用它的示例,但这似乎没有效率,因为我可以将文件存储在 wwroot 文件夹而不是 azure 中。

从 azure 存储读取 csv 文件的最合适方法是什么。

【问题讨论】:

  • 最可能的原因是你的路径错误。如果文件位于虚拟文件夹中,则需要将文件夹包含在文件名中,例如"folder/subfolder/file.jpg"
  • 文件路径是正确的,这就是为什么我可以读取文本文件。
  • 那太奇怪了,因为内容类型不应该影响你下载它的能力。它只是元数据。
  • @juunas...不仅仅是那个文件,我可以下载所有的txt文件,但没有一个csv文件
  • “l”在你传入方法时是小写的,而 blob 名称是大写的。

标签: c# azure csv azure-storage


【解决方案1】:

关于如何逐行遍历,得到内存流后,可以使用StreamReader逐行读取。

示例代码如下:

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

namespace ConsoleApp17
{
    class Program
    {
        static void Main(string[] args)
        {
            string connstr = "your connection string";
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connstr);
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobClient.GetContainerReference("t11");
            CloudBlockBlob blockBlob = container.GetBlockBlobReference("students.csv");
            string text="";
            string temp = "";
            using (var memoryStream = new MemoryStream())
            {
                blockBlob.DownloadToStream(memoryStream);

                //remember set the position to 0
                memoryStream.Position = 0;
                using (var reader = new StreamReader(memoryStream))
                {
                    //read the csv file as per line.
                    while (!reader.EndOfStream && !string.IsNullOrEmpty(temp=reader.ReadLine()))
                    {
                        text = text + "***" + temp;
                    }

                }


            }

            Console.WriteLine(text);
            Console.WriteLine("-------");
            Console.ReadLine();
        }
    }
}

我的 csv 文件:

测试结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 2022-01-15
    • 2021-12-31
    相关资源
    最近更新 更多