Stream无法读取

时间:2018-01-28 07:48:35

标签: 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}");
            }
        }
    }

1 个答案:

答案 0 :(得分:5)

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

responseStream.CopyTo(output);

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

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

(或者,您可以通过复制到MemoryStream将其读入内存,然后您可以重复该流并从中重复读取。但如果您已经将其保存到磁盘,则可能以及那先做。)