Read file from FTP to memory in C#

前端 未结 9 1489
长发绾君心
长发绾君心 2020-12-03 05:15

I want to read a file from a FTP server without downloading it to a local file. I wrote a function but it does not work:

private string GetServerVersion()
{
         


        
9条回答
  •  隐瞒了意图╮
    2020-12-03 05:54

    Small binary file

    If the file is small, the easiest way is using WebClient.DownloadData:

    WebClient client = new WebClient();
    string url = "ftp://ftp.example.com/remote/path/file.zip";
    client.Credentials = new NetworkCredential("username", "password");
    byte[] contents = client.DownloadData(url);
    

    Small text file

    If the small file is a text file, use WebClient.DownloadString:

    string contents = client.DownloadString(url);
    

    It assumes that the file contents is in UTF-8 encoding (a plain ASCII file will do too). If you need to use a different encoding, use WebClient.Encoding property.


    Large binary file

    If the file is large, so that you need to process it in chunks, instead of loading it to memory whole, use FtpWebRequest:

    FtpWebRequest request =
        (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
    request.Credentials = new NetworkCredential("username", "password");
    request.Method = WebRequestMethods.Ftp.DownloadFile;
    
    using (Stream stream = request.GetResponse().GetResponseStream())
    {
        byte[] buffer = new byte[10240];
        int read;
        while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            // process the chunk in "buffer"
        }
    }
    

    Large text file

    If the large file is a text file and you want to process it by lines, instead of by chunks of a fixed size, use StreamReader:

    FtpWebRequest request =
        (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.txt");
    request.Credentials = new NetworkCredential("username", "password");
    request.Method = WebRequestMethods.Ftp.DownloadFile;
    
    using (Stream stream = request.GetResponse().GetResponseStream())
    using (StreamReader reader = new StreamReader(stream))
    {
        while (!reader.EndOfStream)
        {
            string line = reader.ReadLine();
            // process the line
            Console.WriteLine(line);
        }
    }
    

    Again, this assumes UTF-8 encoding. If you want to use another encoding, use an overload of StreamReader constructor that takes also Encoding.

提交回复
热议问题