FTP File upload through C#
Many applications need the ability to upload and download files via FTP. Even automated processes regularly interact with FTP servers for transferring information. Recognizing this, Microsoft has given developers a straight forward technique to implement this functionality. This document focuses on showing the easy way to take advantage of what Microsoft has provided in the. NET Framework.
Before coming to move files around, put a few things to light:
Key points
- Each application will require an object attached to its NetworkCredentials Credentials property. This tells the application how to authenticate against the FTP server.
- The URI provided in order of application must include the name of the file you need to load or unload. For example, if we are downloading the file "data.xml" of abc.ftp.com our ftp://abc.ftp.com/data.xml URI.
- You need to be familiar with the Stream object. We will use this object, both upload and download files.
- These can be simple, when I started moving files to / from FTP servers do not understand some of these concepts, so I thought it would be important! Now go to the code.
Steps to follow
1. Create ftp object
2. Login to ftp server using userid and password
3. Set keepalive property true to multiple use of same instance
4. Use binary method to upload data
5. Set action upload or download
6. Open file in filesteam
7. Read the file in buffer
8. close the filesteam
9. now open ftpsteam
10.write buffer at ftp
11.close the ftp stream
here ftpfilepath is full path of file including file name. and in our case its ftp://abc.ftp.com/data.xml
- public void ftpUpload(string ftpfilepath, string inputfilepath)
- {
- try
- {
- //create ftp object
- FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfilepath);
- // ftp.Credentials = new NetworkCredential("anonymous", "anonymous");
- //userid and password for the ftp server
- ftp.Credentials = new NetworkCredential("ftp_username", "ftp_password");
- //Set keepalive property true to multiple use of same instance
- ftp.KeepAlive = true;
- //use binary method to upload data
- ftp.UseBinary = true;
- //set action (upload or download
- ftp.Method = WebRequestMethods.Ftp.UploadFile;
- //open file in filesteam
- FileStream fs = File.OpenRead(inputfilepath);
- byte[] buffer = new byte[fs.Length];
- //read the file in filestream
- fs.Read(buffer, 0, buffer.Length);
- //close the filesteam
- fs.Close();
- //now open ftpsteam
- Stream ftpstream = ftp.GetRequestStream();
- //write at ftp
- ftpstream.Write(buffer, 0, buffer.Length);
- //close the ftp stream
- ftpstream.Close();
- }
- catch (Exception ex)
- {
- //handle exceptions
- throw;
- }
- }
How to call function
ftpUpload("ftp://abc.ftp.com/data.xml", Server.MapPath("/abc/Documents/") + "temp.xml");
1 comments: