Rob Chartier ~ Contemplation...

.NET, C#, Work, etc.

News






www.flickr.com
This is a Flickr badge showing public photos from Rob & Kat Chartier. Make your own badge here.


Even Quicker Links

Code Snippet: Upload via FTP with .NET v2

Here is a quick code snippet of uploading a file from the local disk, via FTP.

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

byte[] fileContents;

string FinalFile = @"c:\autoexec.bat";

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);

}

 

Posted: May 16 2007, 04:16 PM by Rob Chartier | with 5 comment(s)
Filed under: ,

Comments

Bart said:

Hi,

You declare "byte[] fileContents;", but while uploading you use "zipContents". Is this one just a simple typo ? Or am I missing something ?

Regards,

Bart,

# June 23, 2007 4:53 AM

Richard said:

Rather than manually reading the file with a FileStream, you can simply use:

byte[] fileContents = System.IO.File.ReadAllBytes(FinalFile);

Also, rather than creating a FileInfo simply to extract the file name, you can use the System.IO.Path.GetFileName method:

string uri = string.Format("{0}{1}", FTPServerURI, System.IO.Path.GetFileName(FinalFile));

# July 27, 2007 10:49 AM

ayşe nur said:

hello;

i tried the code above and got the errors below;could you please help me :

   1-The name 'FTPServerURI' does not exist in the current context

   2-The name 'zipContents' does not exist in the current context

# October 27, 2007 5:24 AM

ravi kant said:

Hello

It is giving error in last row:

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

you didn't mention/declare or intialize zipContents,

Please let me know what value need to pass here.

ravikant282@gmail.com

many thanks

# April 11, 2008 11:20 PM

anu said:

.Net ftp upload is found to be time consuming when used in a web application. According to my understanding it may be due to the two way process which occurs ie the http post to the asp.net application and then connecting to the ftp server. Can anyone suggest how to improve ftp performance?

# June 27, 2009 2:12 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)