首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >流不可读

流不可读
EN

Stack Overflow用户
提问于 2018-01-28 15:48:35
回答 1查看 6.3K关注 0票数 2

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

代码语言:javascript
代码运行次数:0
运行
复制
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}");
            }
        }
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-28 15:51:21

您不能从流中读取两次。在此调用之后:

代码语言:javascript
代码运行次数:0
运行
复制
responseStream.CopyTo(output);

..。您已经读取了流中的所有数据。没有什么可读的了,你不能“倒带”流(例如,查找到开头),因为它是一个网络流。诚然,我希望它是空的,而不是抛出错误,但细节并不重要,因为它不是一件有用的事情。

如果您想为同一数据制作两份副本,最好的选择是像您已经在做的那样将其复制到磁盘,然后读取您刚刚写入的文件。

(或者,您可以通过复制到MemoryStream将其读取到内存中,然后您可以倒带该流并重复读取它。但是,如果您已经打算将其保存到磁盘上,那么您不妨先这样做。)

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48484263

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档