Search - Articles - Dev Forums - Favorites - Member Login
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009


Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

FREE 12 month online training for ASP.NET & MS Expression Studio and a Free copy of MS Expression Web with Windows Server Purchase
How to Upload File using FTP in ASP.Net 2.0

Author: Faraz
Download Source Code : 280_FTPRoot.zip

In this article I will try to explain you the technique of uploading file using ASP.Net 2.0.

.Net Framework 2.0 came with many new features which helps the developers in solving daily routines problems/quires while developing an application either windows or desktop. Today as we have seen Web Application became the part of our life. When we are facing any difficulty regarding development we took help from web application, similarly, when we want to purchase any thing we look for e-commerce websites.

 

Since we are a part of 21st century and in this century we have seen many developments in technology. Technology facilitates users in many ways for example, remote universities. Student sitting on one end and university on the other, to transfer course content, lectures etc. usually FTP (File Transfer Protocol) is used. When we talk about .Net Framework 1.0 we didn’t see any facility in using FT Protocol. .Net Framework 2.0 provides us FTPWebRequest and FTPWebResponse classes. These two classes provide complete ease to developers to implement an entire FTP client right from their web application. To get more understanding about these classes consider an example that upload file from local system to ftp://localhost/. You can also transfer file to live servers by providing network credentials (UserID, PWD).

 

To begin with this application create new website in VS2005. Add two controls one is label control and other is button control. Your .aspx source view page looks like this:

 

<asp:Label ID="lblMsg" runat="server"  /><br /><br />

<asp:Button ID="cmdUpload" Text="Upload" runat="server" />

Create a public function named as uploadFileUsingFTP(). This fuction uses four parameters, CompleteFTPPath this parameter is used for passing URL of FTP, CompleteLocalPath used to receive local path. Third and Fourth parameters are UName and PWD used to validate network crediential. Code for this function is as follows:

 

Public Sub uploadFileUsingFTP(ByVal CompleteFTPPath As String, ByVal CompleteLocalPath As String, Optional ByVal UName As String = "",  Optional ByVal PWD As String = "")

 

'Create a FTP Request Object and Specfiy a Complete Path

 Dim reqObj As FtpWebRequest = WebRequest.Create(CompleteFTPPath)

 

'Call A FileUpload Method of FTP Request Object

 reqObj.Method = WebRequestMethods.Ftp.UploadFile

 

'If you want to access Resourse Protected You need to give User Name      and PWD

 reqObj.Credentials = New NetworkCredential(UName, PWD)

 

'FileStream object read file from Local Drive

 Dim streamObj As FileStream = File.OpenRead(CompleteLocalPath)

 

'Store File in Buffer

 Dim buffer(streamObj.Length) As Byte

 

'Read File from Buffer

 streamObj.Read(buffer, 0, buffer.Length)

 

'Close FileStream Object Set its Value to nothing

 streamObj.Close()

 streamObj = Nothing

 

'Upload File to ftp://localHost/ set its object to nothing

 reqObj.GetRequestStream().Write(buffer, 0, buffer.Length)

 reqObj = Nothing

 

End Sub

On cmdUpload_Click function add the following code:

 

Protected Sub cmdUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdUpload.Click

 

'On button Click call the function

'and Pass Parameter Values

'Display Message on Success

 

uploadFileUsingFTP("ftp://localhost/ftp1.txt", "C:\Documents and Settings\Administrator\Desktop\ftp.txt")

lblMsg.Text = "File Uploaded Successfully :)"

 

End Sub

Article Comments
hay plz tell me i want to give option in my course portal project that user can upload and download file from there..i m using asp.net in C#..so plz tell me the code..i will be very thanful to u

Posted on 5/26/2006 12:20:01 AM by NAUMAN

hello Faraz
plz help me .. as i am getting this error " The requested URI is invalid for this FTP command." at this line "reqObj.GetRequestStream().Write(buffer, 0, buffer.Length)"

Posted on 6/1/2006 6:59:47 AM by vikas

First enable the write permission where you want to upload your file at the FTP location.

Posted on 6/2/2006 6:02:50 AM by DevASP

I receive a 530 Not logged in error, anyone has a clue what it could be ?

Posted on 6/6/2006 12:12:27 PM by Peter

I'm getting the "Not logged in" error as well... :'(

Posted on 8/15/2006 8:46:20 AM by Daniel

The code works fine for me. I send it a file to upload and it works. Then I call the proc again with a different file and it fails on "reqObj.GetRequestStream().Write(buffer, 0, buffer.Length)"

with this error "An exception of type 'System.Net.WebException' occurred in System.dll but was not handled in user code"

Posted on 8/16/2006 2:34:42 PM by jack

this is very good, but i want to
know how to use ftp in local machine.
if you do that i am thankful to you

Posted on 9/5/2006 5:18:36 AM by seshu

this is good but I'm having trouble with an error 'Could not find a part of the path ' Even my hosting support is at a loss with whats happening. i just am not able to ftp from the webpage. any ideas? it works when i run it local in vs2005 but not on the actual website. any help would be appreciated. Thanks in advance.

Posted on 9/25/2006 5:17:48 PM by Vincent

How do we write to a subfolder on the ftp host?

Posted on 10/15/2006 12:53:53 PM by ashish

Hello

Can you please provide me any example of FTP Synch.?

Thanks
Sincere Regards

Anoop

Posted on 10/16/2006 1:36:55 PM by Anoop Gupta

When i browse, error flowing, and how I correct ???

"The requested FTP command is not supported when using HTTP proxy."

Posted on 12/5/2006 8:52:32 PM by Khanh ly

Thanks for nice example of actual worknig code rather than just a clip. It's always the part that's not posted that fails. If you have working code for upload and for secure ftp please also post those, thanks.

Posted on 1/11/2007 5:11:45 PM by paul noeldner

how to upload and download the file from ftp location using .Net 2003 or 1.1 version in C#.

Posted on 1/19/2007 1:28:06 AM by Jagannath Sahoo

hello there! How can i run that code in client side? (upload file from users computer)

Thanks

Posted on 5/3/2007 4:27:57 AM by J Widberg

How can i dynamically specify a different source name and location of a file to be uploaded?

Posted on 5/3/2007 8:08:43 AM by Michael O'Donnell

hello Faraz
plz help me .. as i am getting this error " The requested URI is invalid for this FTP command." at this line "reqObj.GetRequestStream().Write(buffer, 0, buffer.Length)"

Posted on 5/10/2007 1:18:22 AM by prabhakar

hello,

this prg works fine but every we have to stop the process then only the file will be uploaded to the ftp server

this is the drawback of this prg other than this is fine and very good

Posted on 5/10/2007 9:04:23 AM by choudhry

Hi the example was really good and its working. But im not able to execute this code from a remote machine. Only working from the local machine. Do i have to add any scripts for that..?? OR any other...?? Please send me a reply
Thanks
Ajith

Posted on 5/12/2007 2:01:14 AM by Ajith Alex M

Hi
Its good working in my app... But i have to upload multiple files and sub directories also

Can we create remote directory?

plz help me..

Posted on 6/22/2007 1:16:05 AM by Murali

Hi Faraz ,

i hava a query about same, when user select file name using file control and file size is moore then 100 mb then will it work or not.
if not then could you please explain me how we can solve this problem?

Posted on 6/26/2007 4:01:36 AM by manish jain

Dear Sirs/Madams

Please help me ! I have trouble with my website uploading. the website is programmed in ASP.net and it is ok to run on my local machine by creating a virtual web server but when I start to upload to the real web server, It has error. Pls follow this link to see the error.

http://www.agribanktour.com/webpages/introduction.aspx

Thank you very much for your help

Best regard,

Luong Trung Kien

Posted on 7/19/2007 3:08:00 AM by Kien

I want to transfer .txt file using FTP and I am making .txt file run time. All these are coded in VB.Net 2003.So please help me as I don't know how to do this.

Posted on 8/7/2007 1:08:01 AM by Hetal Patel

AOA
Hello Faraz may i can use this code to upload file from desktop application to remote web hosting server

Posted on 8/7/2007 3:10:41 AM by Ishfaq

Yeh I've just added a FTP upload portion to a website here is my code in VB. I hope this helps.

Dim localFile As String = System.IO.Path.GetFullPath(btnBrowse.PostedFile.FileName)
Dim remoteFile As String = "ftp://ftp.somesite.com"
Dim username As String = "testuser"
Dim a As Integer
Dim b As Integer
Dim errors As String = "0"

'Splits localfile and takes the last element
Dim ext() As String
ext = Split(localFile, ".")
b = ext.Length - 1

Try
Dim teststream As FileStream = File.OpenRead(localFile)
Dim buffer(teststream.Length) As Byte
teststream.Read(buffer, 0, buffer.Length)
teststream.Close()
teststream = Nothing

'Dim sourceStream As New StreamReader(localFile)
'Dim fileContents As Byte() = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd())
'sourceStream.Close()

'Splits txtSource and takes the last element
Dim fields() As String
fields = Split(localFile, "\")
a = fields.Length - 1

'Get the object used to communicate with the server.
Dim Requested As System.Net.FtpWebRequest = FtpWebRequest.Create(remoteFile & fields(a))
'Requested.ContentLength = fileContents.Length

'Setting Properties
Requested.Credentials = New NetworkCredential(username, txtPassword.Text)
Requested.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Requested.Proxy = Nothing
Requested.KeepAlive = False
Request.IsAuthenticated.ToString()
'Upload file to FTP site
' Dim newstream As Stream = Requested.GetRequestStream
Requested.GetRequestStream().Write(buffer, 0, buffer.Length)
' newstream.Write(fileContents, 0, fileContents.Length)
' newstream.Close(

Posted on 8/8/2007 4:51:43 PM by Rachea

This is very useful.But I am getting an error "The operation has Timed out" when uploading morethan 12 files at once.Upto 12 files it works fine.How to solve this error.Plz advise me.

Thanking you,

RajyaLakshmi.

Posted on 8/16/2007 2:24:31 AM by RajyaLakshmi.M

I got an error while uploading morethan 12 files at once.

The operation has timed out. at

reqObj.GetRequestStream().Write(buffer, 0, buffer.Length). how can i solve this.

But upto 12files it works fine.

Plz solve this Error.

Thanking You,

Harshitha.M

Posted on 8/16/2007 2:55:41 AM by harshitha

Hi,

I got an error while uploading morethan 12 files at once.

The error is: The Operation has Timed out. at the location "reqObj.GetRequestStream().Write(buffer, 0, buffer.Length)".

But it works fine upto 12 files.

How to solve this error when more than 12 files are uploaded.

Thanking You,

Harshitha.M

Posted on 8/16/2007 3:06:41 AM by Harshitha

While uploading a file a file using ftpwebrequest & ftpWebRespose classes, we are facing following error msg. The msg and program line which returns the error msg is given hereunder.


reqObj.GetRequestStream().Write(buffer, 0, buffer.Length)

{"The remote server returned an error: (550) File unavailable (e.g., file not found, no access)."}

Just for refernece while creatign network credentials we are providing windows user credentials who has logged in at client (server & client are on the same machine for testing)


Posted on 8/24/2007 7:06:31 AM by Amit

Thje code presented works perfectly before publishing, after publishing the file in remoteserver, it throws error at 'FileStream object read file from Local Drive

Dim streamObj As FileStream = File.OpenRead(CompleteLocalPath)

i.e system.null reference exception.object not set to instant.

How do i resolve it ? pls help

Posted on 10/9/2007 12:48:11 PM by rprinfo

I could not get this to work either, but the following code changes will give you a more accurate error message:

Try
reqObj.GetRequestStream().Write(buffer, 0, buffer.Length)
Catch ex As WebException
'Access the actual response message from server
Dim status As String = (CType(ex.Response, FtpWebResponse)).StatusDescription
lblMsg.Text &= status
Finally
reqObj = Nothing
End Try

Posted on 10/23/2007 2:25:09 PM by Robert S. Robbins

hi Faraz
plz help me , to upload vedio files to sqlserver2000 in asp.net,
can you provide code for that one.

Posted on 11/2/2007 8:00:03 AM by satish

If you are writing this app from the localhost, where will the file go and upload?

Posted on 11/4/2007 4:47:45 PM by deostroll

Hi Mr. Faraz
it works when i run it local in vs2005 but not on the actual website. any help would be appreciated. Thanks in advance.

Posted on 11/10/2007 1:22:24 AM by Gilbert Figueroa

zip file upload to the ftp server,but can not open zip file.pls help me.

Posted on 11/17/2007 5:24:32 AM by pradeep

i want to upload zip file using ftp.i upload zip file to the ftp server,but uploaded file size(8000K) and local file(16000K) size different file size.plz help me.

Posted on 11/17/2007 5:29:03 AM by pradeep

are you trying to make somone fool? this code cant run at www website. because it refers local path which is meaningless on server site at www website's server.

Posted on 11/28/2007 11:03:10 PM by pravin

are you trying to make somone fool? this code cant run at www website. because it refers local path which is meaningless on server site at www website's server.

Posted on 11/28/2007 11:03:49 PM by pravin parmar

I am trying to uploading .pdf file from this code,File is uploaded but .pdf file is empty(content is not present in the page)

Posted on 12/4/2007 3:23:53 AM by check

Hi Faraz,

i tried to upload a zip file using this code. File gets uploaded but the uploaded zip file gets corrupted... is there any other way to upload zip files??

Posted on 12/6/2007 2:07:45 AM by Gagan

Very good sample, just one little comment:
"reqObj.GetRequestStream().Write(buffer, 0, buffer.Length)"
should be
buffer.Length - 1

Greetz,
P

Posted on 12/18/2007 5:07:47 PM by thoughtcriminal

Very good sample, just one little comment:
"reqObj.GetRequestStream().Write(buffer, 0, buffer.Length)"
should be
buffer.Length - 1

Greetz,
P

Posted on 12/18/2007 5:08:18 PM by thoughtcriminal

hello Faraz
I used this code but I got Error-"The remote server returned an error: (550) File unavailable (e.g., file not found, no access)."
so plz help me to solve this error.
Actually I want to upload my file from local machin to server.

Posted on 12/21/2007 4:04:40 AM by Parag

It's cool....
Thank you

Posted on 12/28/2007 2:20:06 AM by Francis

Thank you very much for this article but I'm having the same problem as vincent : the error 'Could not find a part of the path ' "it works when i run it local in vs2005 but not on the actual website". can you please give me a hint how to solve this? Thanks very much in advance.

Posted on 1/18/2008 6:58:41 AM by Leen

Thanks for this nice code.

I noticed one problem though; when I look at the file that has been uploaded on ftp, there are extra carriage return/line feed inserted between each line in a text file.

Ex: Original file text:

asdf
asdf
asdf
asdf

Uploaded file text:
asdf

asdf

asdf

asdf


I'm not sure what to do about that - any ideas?

Thanks

Posted on 1/28/2008 6:16:14 PM by Zach

When i send text file, that file is created in other computer(remote) but there content is not send or (0 KB)

2> when i open a received file then file is not open

3> When i send again same file by using .net then error
-> file not fount
-> or access denied

plz ans me quickly

Posted on 2/1/2008 6:46:14 AM by girish

The function seemed to work perfect but the file is 280kb but only the first 30kb is copied.
Is there some setting to increase the max filesize?

Thanks,
Micha

Posted on 3/12/2008 6:58:07 AM by Micha Brans

Fukin cool man! Saved me a lot of work! Tanks and keep up the good job :)

Posted on 4/8/2008 8:40:50 PM by CMC

hi. this is a nice article, and if only i could get it to work! a file is created on the server with the same name, but it is an empty file! i tried it with a couple of formats, but it always had the same result! please do assist me if time allows.
thanking you, terence

Posted on 4/9/2008 5:38:06 AM by terence

Hi, I don't see a date on here and I need some help please.
I am getting an error in your code:

Cannot implicitly convert type 'System.Net.WebRequest' to 'System.Net.FtpWebRequest'. An explicit conversion exists (are you missing a cast?)

Posted on 4/16/2008 4:13:42 AM by Alon Chalmers

I tried this code. 10 days before it works fine. but now i upload new file it gives me an error. it does not read file from my local pc. error is "Could not find file 'C:\Documents and Settings\Administrator\Desktop\ftp.txt'.". what can i do for now ? Please tell me. its very argent. thanks a lot in advance..

Posted on 5/2/2008 3:02:04 AM by Sejal

I developed an application to upload the images. I deployed my website on hosting server. I want to upload images in a directory located in my deployed website. But when i run website on my PC it uploads the image on the host server but when i run the website from internet then it throws the following error:

Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

can someone help me regarding this problem.

Posted on 5/22/2008 8:50:25 AM by Jawad Naeem

thanks dear Faraz!!!!!!!!!

Posted on 5/25/2008 4:38:56 AM by Hamid

I am trying to upload files on FTP and used the code below:

Dim request As FtpWebRequest

request =
WebRequest.Create("ftp://ftp...../test.txt")
request.Method = WebRequestMethods.Ftp.UploadFile
request.Credentials = New
NetworkCredential(ftp_site_user_name, ftp_site_password)

Dim sourceStream As New
StreamReader("C:\Documents and Settings\.......\text.txt")

Dim filecontents() As Byte =
Encoding.UTF8.GetBytes(sourceStream.ReadToEnd())

sourceStream.Close()
request.ContentLength = filecontents.Length

Dim requestStream As Stream =
request.GetRequestStream()
requestStream.Write(filecontents, 0,
filecontents.Length)
requestStream.Close()

When I define to use proxy
(Dim proxy As IWebProxy = New
WebProxy("172.x.x.x", 21)
clsRequest.Proxy = proxy)
I receive an error "The requested FTP command is not
supported when using HTTP proxy". When I define NOT to use proxy, the
file is not uploaded on FTP.

1. How do i achieve this?

2. Can I create subdirectories on FTP from code ?

3. StreamReader reads TXT files. How can I read ZIP files for uploading
on FTP ?

Thanks
Arun

Posted on 9/18/2008 5:42:49 AM by arun

Hi, the example was really good and its working. But i am not able to execute this code from a remote machine. Only working from the local machine. can u please help

Posted on 10/28/2008 3:21:21 AM by chaitanya

//C# Equivalent
using System.IO;
using System.Net;

namespace ftpupload
{
public class ftpupload
{

public void uploadFileUsingFTP(string CompleteFTPPath, string CompleteLocalPath, string UName, string PWD)
{
//Create a FTP Request Object and Specfiy a Complete Path
FtpWebRequest reqObj = (FtpWebRequest)WebRequest.Create(CompleteFTPPath);
//Call A FileUpload Method of FTP Request Object
reqObj.Method = WebRequestMethods.Ftp.UploadFile;
//If you want to access Resourse Protected You need to give User Name and PWD
reqObj.Credentials = new NetworkCredential(UName, PWD);
//FileStream object read file from Local Drive
FileStream streamObj = File.OpenRead(CompleteLocalPath);
//Store File in Buffer
byte[] buffer = new byte[streamObj.Length + 1];
//Read File from Buffer
streamObj.Read(buffer, 0, buffer.Length);
//Close FileStream Object Set its Value to nothing
streamObj.Close();
//Upload File to ftp://localHost/ set its object to nothing
reqObj.GetRequestStream().Write(buffer, 0, buffer.Length);
}
}
}

Posted on 12/4/2008 8:09:42 AM by Senguttuvan G

thanks.....

Posted on 11/21/2009 7:41:12 AM by Murali

Dear developer,
I really appreciate this smart way of uploading a file, I have been strangling to upload large files for web applications for my clinets. because the server is timing out if the file is more then 15-20 MB, and i assuem this will fix that issue correct? i will try it soon and thank you so much for this greate example.

Posted on 12/4/2009 11:14:27 AM by nazo tajrian

Thanks

Posted on 12/29/2009 2:12:05 AM by chekuri.ravikumar

CompleteFTPPath i cant understand what is this ,in my rum have two systems with net,how i transfer a file local system to remote system


please give response with correct answer.....
i am waiting for ur answer

Posted on 1/25/2010 2:24:05 AM by satya

How i print prime numbers among 1 to 200

Posted on 1/29/2010 6:01:12 AM by pradeep kumar

Nice code but when we execute with mozilla or firefox getting error of local file path. so how to resolve in mozilla. In IE it is working fine.

Posted on 2/9/2010 2:37:27 AM by Ashutosh

Hi i am new to c# and asp. i am doing an application to transfer image file using ftp. i am using asp and c#. please can you send me the sample code for c#?

Posted on 3/3/2010 4:43:13 AM by Paul

Hi All,

It was very nice to have such ready made code. Thanks.....

Hi Paul: I think Senguttuvan already answered your question. Please see his comments.

Posted on 3/18/2010 1:38:08 PM by Bharath Reddy VasiReddy

i get an exception @ below line
reqObj.GetRequestStream().Write(buffer, 0, buffer.Length)

saying
The remote server returned an error: (501) Syntax error in parameters or arguments.

Please let me know the solution for this exception.

Posted on 3/22/2010 5:37:39 AM by srinsoft

Hi Friends,
Kindly share me the code, if its working for you...


Thank You

Posted on 3/23/2010 12:21:56 PM by krishna

Sir

After copying all files from local to ftp..i want to check if files uploaded with proper size then ok other wise show error.

Posted on 4/19/2010 1:29:35 AM by Sandeep rana

The sample at the top of the page, run perfecty in local, but when I save the code in the web server don't work.
the webserver don't know where is the file what I want to up to Webserver because is in my computer.
I need Help, can you tell my what I must to do?

Posted on 6/3/2010 3:42:17 PM by Bach

Thank you for the clear example. I was struggling with how to connect to the remote host and your example helped me to resolve my issues.

Posted on 6/9/2010 2:10:39 PM by LeeAnn

Works like a charm!!! You have saved me lot of time !!

Cheers

Posted on 6/15/2010 10:49:25 PM by Dev

we want to upload an image on our website in asp.net during runtime. please help us and provide us the code.
as soon as possible

Posted on 8/27/2010 9:03:43 AM by rajat tiwari

Struggled all day with this and still not able to upload a file. After reading this over and over again I finally noticed that this is a FTP to a "local" machine. Anyone got a version to ftp to a remote server?

Posted on 8/27/2010 11:51:52 AM by Gerry

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< HTML encoding/decoding in ASP.Net 2.0

Disclaimer - Privacy
© 2002-2010 DevASP.net