简体   繁体   English

在 C# 中从 MemoryStream 更改为 Stream

[英]Changing from MemoryStream to Stream in C#

Below is the code where I am passing memory stream and reading it and doing the necessary operation afterwards.下面是我传递 memory stream 并读取它并在之后进行必要操作的代码。 Now the requirement has changed and instead of Memory stream, I will be passing Stream and that starts giving me error.现在要求已经改变,而不是 Memory stream,我将通过 Stream 并开始给我错误。 I would like to know how can I handle the below method if contents returned here is of Stream type.如果此处返回的内容是 Stream 类型,我想知道如何处理以下方法。 Now it works fine when my contents is of type MemoryStream.现在,当我的内容是 MemoryStream 类型时,它可以正常工作。

public async Task<string> ReadStream(string containerName, string digestFileName, string fileName, string connectionString)
        {
            string data = string.Empty;
            string fileExtension = Path.GetExtension(fileName);
            var 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;
        }

I'm going to assume the issue is contents.ToArray() , since Stream desn't have a ToArray() method.我将假设问题是contents.ToArray() ,因为Stream没有ToArray()方法。

In this case, you'll be better off using a StreamReader :在这种情况下,最好使用StreamReader

using (var reader = new StreamReader(contents))
{
    data = reader.ReadToEnd();
}

StreamReader uses Encoding.UTF8 by default, but you can specify it explicitly if you want: new StreamReader(contents, Encoding.UTF8) . StreamReader默认使用Encoding.UTF8 ,但您可以根据需要明确指定它: new StreamReader(contents, Encoding.UTF8)

You'll note that you're already doing this a few lines above, to read from the unzipper stream.您会注意到,您已经在上面的几行中执行此操作,以从解压缩器unzipper中读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM