简体   繁体   English

从FTP响应中返回流读取器是否良好实践

[英]Return stream reader from FTP response is good practice or not

I have a method for FTP download file, but I do not save file locally rather I parse the file in memory through ftp response. 我有一个FTP下载文件的方法,但我不在本地保存文件,而是通过ftp响应解析内存中的文件。 My question is, is returning stream reader after getting ftp response stream a good practice? 我的问题是,获得ftp响应流后返回流读取器是一个好习惯吗? Because do not want to do parsing and other stuff in the same method. 因为不想在同一个方法中进行解析和其他东西。

var uri = new Uri(string.Format("ftp://{0}/{1}/{2}", "somevalue",     remotefolderpath, remotefilename));
var request = (FtpWebRequest)FtpWebRequest.Create(uri);
request.Credentials = new NetworkCredential(userName, password);

request.Method = WebRequestMethods.Ftp.DownloadFile;

var ftpResponse = (FtpWebResponse)request.GetResponse();
/* Get the FTP Server's Response Stream */
ftpStream = ftpResponse.GetResponseStream();
return responseStream = new StreamReader(ftpStream);

I see more practical returning a responseStream when you are performing an HttpWebRequest . 当你执行HttpWebRequest时,我看到更实用的返回responseStream。 If you are using FtpWebRequest it means you are working with files. 如果您使用的是FtpWebRequest则表示您正在处理文件。 I would read the responseStream to byte[] and return the byte file content of the downloaded file, so you can easily work with the System.IO.File classes to handle the file. 我会将responseStream读取到byte []并返回下载文件的字节文件内容,这样您就可以轻松使用System.IO.File类来处理该文件。

For me there are 2 disadvantages of using the stream directly, if you can live with them, you shouldn't waste memory or disk space. 对我来说直接使用流有两个缺点,如果你可以使用它,你不应该浪费内存或磁盘空间。

  • In this stream you can not seek to a specific position, you can only read the contents as it comes in; 在此流中,您无法寻找特定的位置,只能读取内容;
  • Your internet connection could suddenly drop and you will get an exception while parsing and processing your file, either split the parsing and processing or make sure your processing routine can handle the case that a file is processed for a second time (after a failure halfway through the first attempt). 您的互联网连接可能会突然丢失,您在解析和处理文件时会遇到异常,要么拆分解析和处理,要么确保您的处理例程可以处理文件第二次处理的情况(中途失败后)第一次尝试)。

To work around these issues, you could copy the stream to a MemoryStream: 要解决这些问题,可以将流复制到MemoryStream:

using (var ftpStream = ftpResponse.GetResponseStream())    
{
   var memoryStream = new MemoryStream()
   while ((bytesRead = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
   {
      memoryStream.Write(buffer, 0, bytesRead);
   }  

   memoryStream.Flush();
   memoryStream.Position = 0;
   return memoryStream;                   
}

If you are working with larger files I prefer writing it to a file, this way you minimize the memory footprint of your application: 如果您正在使用较大的文件,我更喜欢将其写入文件,这样可以最大限度地减少应用程序的内存占用量:

using (var ftpStream = ftpResponse.GetResponseStream())    
{
   var fileStream = new FileStream(Path.GetTempFileName(), FileMode.CreateNew)
   while ((bytesRead = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
   {
      fileStream.Write(buffer, 0, bytesRead);
   }  

   fileStream.Flush();      
   fileStream.Position = 0;
   return fileStream;
}

Thanks Carlos it was really helpful . 谢谢卡洛斯,这真的很有帮助。 I just return the byte[] 我只是返回字节[]

           byte[] buffer = new byte[16 * 1024];

           using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
               memoryStream=ms;
            }
         return memoryStream.ToArray();

and used byte[] in the method like this 并在这样的方法中使用byte []

   public async Task ParseReport(byte[] bytesRead)
    {
        Stream stream = new MemoryStream(bytesRead);
        using (StreamReader reader = new StreamReader(stream))
            {
            string line = null;
            while (null != (line = reader.ReadLine())) 
            {
              string[] values = line.Split(';');
            }
            }
        stream.Close();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM