Pages

Showing posts with label FTP. Show all posts
Showing posts with label FTP. Show all posts

Tuesday 9 June 2015

Upload file to FTP from windows form applications

Overview : Sometimes we need to upload some files to a web server from our desktop application. The file upload task is pretty easy in web applications but in desktop applications it is confusing because in websites we upload the files on the same server where we are working but in desktop applications we are working on a local computer and the server is come where else.
To overcome this issue I have created a function which will do this task for you.

public static void Fileuploader(string localpath, string username, string password)
        {
            var fileName = Path.GetFileName(localpath);
            var request = (FtpWebRequest)WebRequest.Create("ftp://www.example.com/httpdocs/_sft0258/" + fileName);

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

            using (var fileStream = File.OpenRead(localpath))
            {
                using (var requestStream = request.GetRequestStream())
                {
                    fileStream.CopyTo(requestStream);
                    requestStream.Close();
                }
            }

            var response = (FtpWebResponse)request.GetResponse();
            Console.WriteLine("Success: {0}", response.StatusDescription);
            response.Close();
        }


By calling this function with correct parameters the upload file task will be completed smoothly.