Stream was not readable

I have code below that read ftp response stream and write data to two different files (test1.html & test2.html). The 2nd StreamReader throw a stream was not readable error. The response stream should be readable because it's not out of scope yet and the dispose shouldn't be called. Can someone explain why?

static void Main(string[] args)
    {
        // Make sure it is ftp
        if (Properties.Settings.Default.FtpEndpoint.Split(':')[0] != Uri.UriSchemeFtp) return;

        // Intitalize object to used to communicuate to the ftp server
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(Properties.Settings.Default.FtpEndpoint + "/test.html");

        // Credentials
        request.Credentials = new NetworkCredential(Properties.Settings.Default.FtpUser, Properties.Settings.Default.FtpPassword);

        // Set command method to download
        request.Method = WebRequestMethods.Ftp.DownloadFile;

        // Get response
        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        using (Stream output = File.OpenWrite(@"C:\Sandbox\vs_projects\FTP\FTP_Download\test1.html"))
        using (Stream responseStream = response.GetResponseStream())
        {
            responseStream.CopyTo(output);
            Console.WriteLine("Successfully wrote stream to test.html");

            try
            {
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    string file = reader.ReadToEnd();
                    File.WriteAllText(@"C:\Sandbox\vs_projects\FTP\FTP_Download\test2.html", file);

                    Console.WriteLine("Successfully wrote stream to test2.html");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception: {ex}");
            }
        }
    }
Jon Skeet
people
quotationmark

You can't read from the stream twice. After this call:

responseStream.CopyTo(output);

... you've already read all the data in the stream. There's nothing left to read, and you can't "rewind" the stream (e.g. seeking to the beginning) because it's a network stream. Admittedly I'd expect it to just be empty rather than throwing an error, but the details don't really matter much as it's not a useful thing to try to do.

If you want to make two copies of the same data, the best option is to copy it to disk as you're already doing, then read the file that you've just written.

(Alternatively, you could just read it into memory by copying to a MemoryStream, then you can rewind that stream and read from it repeatedly. But if you're already going to save it to disk, you might as well do that first.)

people

See more on this question at Stackoverflow