Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 流不可读_C# - Fatal编程技术网

C# 流不可读

C# 流不可读,c#,C#,下面的代码读取ftp响应流并将数据写入两个不同的文件(test1.html和test2.html)。第二个StreamReader抛出的流不可读错误。响应流应该是可读的,因为它还没有超出范围,并且不应该调用dispose。有人能解释一下原因吗 static void Main(string[] args) { // Make sure it is ftp if (Properties.Settings.Default.FtpEndpoint.Split('

下面的代码读取ftp响应流并将数据写入两个不同的文件(test1.html和test2.html)。第二个
StreamReader
抛出的
流不可读
错误。响应流应该是可读的,因为它还没有超出范围,并且不应该调用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}");
            }
        }
    }

你不能从流中读取两次。在这通电话之后:

responseStream.CopyTo(output);
。。。您已经读取了流中的所有数据。没有任何内容可供阅读,并且您无法“倒带”流(例如,查找到开头),因为它是一个网络流。诚然,我希望它只是空的,而不是抛出一个错误,但是细节并不重要,因为它不是一件有用的事情

如果您想对同一数据进行两次复制,最好的选择是将其复制到磁盘,就像您已经在做的那样,然后读取刚刚写入的文件


(或者,您可以通过复制到
MemoryStream
将其读入内存,然后您可以倒带该流并重复读取。但如果您已经打算将其保存到磁盘,您最好先这样做。)

请注意,问题的一个重要部分是,代码正在从无法搜索的网络流中读取。若一个用于处理文件/内存流,那个么您可以根据需要多次查找并再次读取该流。也可以有只读/只读流,但您可能必须自己编写一个。@AlexeiLevenkov:是的。。。尽管即使在“可倒带”的情况下,原始代码也无法工作。请注意,您不能倒带网络流。