Ankit Kumar
Ankit Kumar

Reputation: 514

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. Now the requirement has changed and instead of Memory stream, I will be passing Stream and that starts giving me error. I would like to know how can I handle the below method if contents returned here is of Stream type. Now it works fine when my contents is of type 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;
        }

Upvotes: 0

Views: 1758

Answers (1)

canton7
canton7

Reputation: 42225

I'm going to assume the issue is contents.ToArray(), since Stream desn't have a ToArray() method.

In this case, you'll be better off using a 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).

You'll note that you're already doing this a few lines above, to read from the unzipper stream.

Upvotes: 5

Related Questions