首页 > 解决方案 > 在 C# 中读取 Gzip 文件的问题

问题描述

使用以下方法,我正在尝试读取 .gz 文件,但出现错误,因为"Stream does not support reading. (Parameter 'stream')"。我对这个错误一无所知,想知道这意味着什么,如果可能的话,有什么修复它的建议。文件是这种格式 test1.csv.gz 并且错误在行返回 using(var unzipper....

public async Task<string> ReadStream(string containerName, string digestFileName,string fileName, string connectionString)
{
    string data = string.Empty;
    string fileExtension = Path.GetExtension(fileName);
    MemoryStream contents = await DownloadBlob(containerName, digestFileName, connectionString);
    if (fileExtension == ".gz")
    {
        using (var unzipper = new GZipStream(contents, CompressionMode.Decompress))
        using (StreamReader reader = new StreamReader(unzipper, Encoding.UTF8))
        {
            data = reader.ReadToEnd();
        }
    }
    else
    {
       data = Encoding.UTF8.GetString(contents.ToArray());
    }
    return data;
}

下载Blob:

public async Task<MemoryStream> DownloadBlob(string containerName, string fileName, string connectionString)
{
    MemoryStream memoryStream = new MemoryStream();            
    Microsoft.Azure.Storage.CloudStorageAccount storageAccount = Microsoft.Azure.Storage.CloudStorageAccount.Parse(connectionString);
    CloudBlobClient serviceClient = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = serviceClient.GetContainerReference(containerName);
    CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
    if (blob.Exists())
        using (memoryStream = new MemoryStream())
        {
            await blob.DownloadToStreamAsync(memoryStream);
        }
    return memoryStream;
}

标签: c#

解决方案


通过您的using声明,您可以处理流。

不要在那里这样做,调用者应该这样做。


推荐阅读