gpt4 book ai didi

c# - 流不可读

转载 作者:太空宇宙 更新时间:2023-11-03 19:44:08 26 4
gpt4 key购买 nike

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

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 将它读入内存,然后您可以倒回该流并重复读取它。但是如果您已经打算将它保存到磁盘,你不妨先这样做。)

关于c# - 流不可读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48484263/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com