下面是读取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}");
}
}
}
发布于 2018-01-28 07:51:21
您不能从流中读取两次。在此调用之后:
responseStream.CopyTo(output);
..。您已经读取了流中的所有数据。没有什么可读的了,你不能“倒带”流(例如,查找到开头),因为它是一个网络流。诚然,我希望它是空的,而不是抛出错误,但细节并不重要,因为它不是一件有用的事情。
如果您想为同一数据制作两份副本,最好的选择是像您已经在做的那样将其复制到磁盘,然后读取您刚刚写入的文件。
(或者,您可以通过复制到MemoryStream
将其读取到内存中,然后您可以倒带该流并重复读取它。但是,如果您已经打算将其保存到磁盘上,那么您不妨先这样做。)
https://stackoverflow.com/questions/48484263
复制相似问题