Stream无法读取

Jas*_*ang 1 c#

我有下面的代码读取ftp响应流并将数据写入两个不同的文件(test1.html和test2.html).第二次StreamReader抛出一个stream was not readable错误.响应流应该是可读的,因为它还没有超出范围,并且不应该调用dispose.有人可以解释原因吗?

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}");
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

您无法从流中读取两次.通话结束后:

responseStream.CopyTo(output);
Run Code Online (Sandbox Code Playgroud)

...您已经阅读了流中的所有数据.没有什么可以阅读,你不能"回放"流(例如寻找到开头),因为它是一个网络流.不可否认,我希望它只是空洞而不是抛出错误,但细节并不重要,因为尝试这样做并不是一件有用的事情.

如果要制作相同数据的两个副本,最好的选择是将其复制到磁盘上,然后读取刚写入的文件.

(或者,您可以通过复制到a来将其读入内存MemoryStream,然后您可以重复该流并从中重复读取.但是如果您已经将它保存到磁盘,那么您最好先这样做.)