Upload files using FTP with .NET

This code sample shows how to use C# code to programmatically upload files to an ftp server.

// get the contents of the file you want to upload

byte[] fileContents;

string FinalFile = @"c:\MyFile.txt";
using(System.IO.FileStream fs = new System.IO.FileStream(FinalFile, System.IO.FileMode.Open)) {

fileContents = new byte[fs.Length];
fs.Read(fileContents, 0, (int)fs.Length);

}

//get the filename, append it to the URL
System.IO.FileInfo fi = new System.IO.FileInfo(FinalFile);

//FTPServerURI must be in the format of:

//ftp://user:password@ftp.myserver.com:21/path/to/upload/folder/
string uri = string.Format("{0}{1}", FTPServerURI, fi.Name);

//now we have:

//ftp://user:password@ftp.myserver.com:21/path/to/upload/folder/autoexec.bat

//create the ftp request
System.Net.WebRequest request = System.Net.FtpWebRequest.Create(uri);

//state that we uploading the file
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile;

//get the request stream
using (System.IO.Stream stm = request.GetRequestStream()) {

//write the contents of the file up

stm.Write(zipContents, 0, zipContents.Length);

}


Comments

Author: subbarayudu14 Aug 2008 Member Level: Gold   Points : 2

Hi
I am also using your code and all but i am unable to follow just give me confirmation regarding
FTPServerURI --- instead of
I am giving
like this
ftp://vamsi:krishna@192.168.1.91:D:/vamsi/
// what u given in code i written like this , this is source or destination IP address i dont know

//ftp://user:password@ftp.myserver.com:21/path/to/upload/folder/
string uri = string.Format("{0}{1}", FTPServerURI, fi.Name);1

bottom of this code u given
stm.Write(zipContents, 0, zipContents.Length);
what is zipContents it is given error does not exist like this it is giving error



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: