Gali
Gali

Reputation: 14973

hot to transfer from FTP to local directory on my computer in C#

i have FTP server in my computer (Windows-7) called MyFTP

i have thit code to transfer from local directory to FTP server

this code work excellent

string MyFile = @"d:\Test.txt";

            //string url = "ftpUrl/FileName";
            string url = "ftp://127.0.0.1/Test.txt";

            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(url);

            request.Method = WebRequestMethods.Ftp.UploadFile;
            //request.Credentials = new NetworkCredential("user name", "password");
            request.UsePassive = true;
            request.UseBinary = true;
            request.KeepAlive = false;


            byte[] buffer = File.ReadAllBytes(MyFile);

            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(buffer, 0, buffer.Length);
            }

and now i need to to transfer from FTP server to local directory in my computer

how to do it ?

Upvotes: 0

Views: 2111

Answers (2)

Xiol
Xiol

Reputation: 169

If you need to use the FtpWebRequest this should get the job done

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://127.0.0.1/Test.txt");
request.Method = WebRequestMethods.Ftp.DownloadFile;
//request.Credentials = new NetworkCredential("user name", "password");
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;

byte[] data;

using (var responce = request.GetResponse())
using (var stream = responce.GetResponseStream())
using (var reader = new BinaryReader(stream))
{
     data = reader.ReadBytes((int)stream.Length);
}

I know there are more efficient and safe ways to empty the stream. but this will work.

Upvotes: 0

kenwarner
kenwarner

Reputation: 29140

I'd suggest using WebClient, the API is a little easier

using (WebClient ftpClient = new WebClient())
{
    ftpClient.Credentials = new System.Net.NetworkCredential("username", "password");
    ftpClient.DownloadFile("ftp://127.0.0.1/destination.txt", "C:\\source.txt");
}

Upvotes: 4

Related Questions