Custom Search
Logiclabz
  • Home
  • C#
  • FTP File Upload using FtpWebRequest in .Net C#

FTP File Upload using FtpWebRequest in .Net C#

  

FtpWebRequest Class in System.Net namespace helps in implementing a File Transfer Protocol (FTP) client in .Net.
To obtain an instance of FtpWebRequest, use the Create method.
The URI is of the form "ftp://127.0.0.1/path", first the .NET Framework logs into the FTP server using the user name and password set by the Credentials property, then the current directory is set to <UserDirectory>/path.
FtpWebRequest.KeepAlive specifies whether the control connection to the FTP server is closed after the request completes.
FtpWebRequest.UseBinary specifies the data type for file transfers.
FtpWebRequest.Method sets the command to send to the FTP server.
WebRequestMethods.Ftp.UploadFile Field represents the FTP STOR protocol method that uploads a file to an FTP server.
When using an FtpWebRequest object to upload a file to a server, you must write the file content to the request stream obtained by calling the GetRequestStream method.
You must write to the stream and close the stream before sending the request.

Namespace used:

using System.Net;
using System.IO;

Sample Code:
    public void ftpfile(string ftpfilepath, string inputfilepath)
    {
        string ftphost = "127.0.0.1";
        //here correct hostname or IP of the ftp server to be given

        string ftpfullpath = "ftp://" + ftphost + ftpfilepath;
        FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
        ftp.Credentials = new NetworkCredential("userid", "password");
        //userid and password for the ftp server to given

        ftp.KeepAlive = true;
        ftp.UseBinary = true;
        ftp.Method = WebRequestMethods.Ftp.UploadFile;
        FileStream fs = File.OpenRead(inputfilepath);
        byte[] buffer = new byte[fs.Length];
        fs.Read(buffer, 0, buffer.Length);
        fs.Close();
        Stream ftpstream = ftp.GetRequestStream();
        ftpstream.Write(buffer, 0, buffer.Length);
        ftpstream.Close();
    }

Function can be used as
ftpfile(@"/testfolder/testfile.xml", @"c:\testfile.xml");



  


Leave a reply


Comments

  • Tim says:
    Jul 28, 09

    Really useful piece of code. Thanks for this!

  • Muzi says:
    Dec 10, 09

    Thanks great article! I have a problem uploading big files, could kindly suggest a method for uploading big file and different file types? thanks in advance

  • jashwant says:
    Feb 13, 10

    I am using Fileupload (asp.net 3.5) I do not want to give 'inputfilepath' deliberately. Is there any method, so that the file selected from FileUpload can be sent via ftp ??/

  • Edms says:
    Mar 19, 10

    I have a similar code, it works but the file turns into and unrecognised format file. for eg, trial.txt turns into trial any solution to this??

  • Srinivasan says:
    Mar 22, 10

    i get an exception @ below line Stream ftpstream = ftp.GetRequestStream(); saying The remote server returned an error: (501) Syntax error in parameters or arguments. Please let me know the solution for this exception.

  • Larry says:
    Mar 25, 10

    I get "Cannot re-call BeginGetRequestStream/BeginGetResponse while a previous call is still in progress" when I do ftpstream.Close(), anyone got any idea on how I can check if the call is still in progress?

  • Ashish says:
    Jun 23, 10

    Really useful piece of code.

  • Candido says:
    Jun 24, 10

    Excelent code. It really works well in most FTP servers. But in some FTP servers I get a 501 error. Any ideas why? Usually 501 error is due to not implemented errors.

  • GoingPostal says:
    Jun 24, 10

    This code won't work if you sit behind a web proxy ;)

  • piyush says:
    Jul 01, 10

    i get error on below line Stream ftpstream = ftp.GetRequestStream(); saying The remote server returned an error: (550) File unavailable (e.g., file not found, no access).

  • piyush says:
    Jul 01, 10

    coulde u plz give me solution about it!

  • Amit wadaskar says:
    Oct 19, 10

    This is code is not running properly and i'm feeling difficulty to understand it so please send me another simple code.

  • Jyothish says:
    Nov 15, 10

    Hi All I got the same error: (550) File unavailable (e.g., file not found, no access). But i have tried to upload a file to the root folder. It is working fine. If i tried to upload the file to a non existing folder then it will throws the error.

  • ashish says:
    Dec 11, 10

    i used as per your code for file upload in ftp server that give the error could not find file but that code work well in localhost to ftp server.

  • Eugene says:
    Jan 12, 11

    Great article, and very useful code. Thank you for make it done.

  • Alex says:
    Jan 23, 11

    Thank you so much... Very useful, fully functional piece of code.

  • Gaurav Bajpai says:
    Feb 13, 11

    it is really great.... :)

  • Carol says:
    Apr 11, 11

    I got this to work fine: Read entire file into memory. Upload in 4k chunks. How would I get this working instead: Read 4k chunks into memory. Upload in 4k chunks.

  • Flash Game says:
    Apr 14, 11

    Thanks. Very usefull. I use this code for my site.

  • Scot says:
    May 04, 11

    The code does not work for me. I get an error message: http://webtvpc.net/index.aspx?site=www.mortgage-pros.com&width-=114&height=82

  • henry says:
    May 17, 11

    Works fine.Thanks

  • amir says:
    Jun 18, 11

    i want a error The remote server returned an error: (530) Not logged in.

  • Shahab Abbasi says:
    Jun 29, 11

    Hi..Thanks for providing the code. Can you please tell me, if the file that i am uploading already exists on the ftp server. Then does it work because i need to replace my xml file with the existing file...Please reply.

  • Joseph says:
    Jun 30, 11

    I am getting this error System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) at System.Security.CodeAccessPermission.Demand() at System.IO.FileInfo..ctor(String fileName) at _Default.UploadFile(String _FileName, String _UploadPath, String _FTPUser, String _FTPPass) at _Default.Button1_Click(Object sender, EventArgs e) The action that failed was: Demand The type of the first permission that failed was: System.Security.Permissions.FileIOPermission The Zone of the assembly that failed was: MyComputer

  • Abdul says:
    Aug 02, 11

    sometime my XML file is not transferring and showing in FTP the file with 0 Kb size. how i can solve this issue?

  • Javie Westerfield says:
    Nov 01, 11

    I am getting an InvalidOperationException in C# using this code with an error of "The requested FTP command is not supported when using HTTP proxy". I thought that since we are using ftp:// in te fullpath that this would override the HTTP proxy. Anybody have an idea why I'm getting this?

  • vijay says:
    Jan 03, 12

    but this transfers file on local system only not on remote system once appliation is deployed hope this blog is live....

  • madhu says:
    Feb 28, 12

    I found Something , here is detailed Explanation http://path4tech.blogspot.in/2012/02/upload-file-to-ftp-server-by-using.html

  • Circle Pro says:
    Mar 17, 12

    Very aptly presented and put forward. this is a great blog post. Gives Fodder for brain as well as compells you to ponder. Happy That I stumbled upon this site.

  • Madhu K P says:
    Mar 19, 12

    Thank you. This code worked perfectly.

  • identity lookout says:
    Mar 22, 12

    Its seldom that you find such blog posts. Well written and aptly presented. good work. Will follow this post.

  • prathap says:
    May 12, 12

    hi, when i deployed the same code on server it is not working,but locally it is working, i am getting the as System.UnauthorizedAccessException: Access to the path 'E:\links.txt' is denied. can u please tell me the code for deploying in server



Do you like this post?