# VBForums CodeBank > CodeBank - Visual Basic .NET >  Upload File via FTP (VB.NET 2005)

## met0555

this code will let you upload a file on an ftp server. working on vb.net 2005
i hope it will help u


Upload via FTP Code:
' set up request...
        Dim clsRequest As System.Net.FtpWebRequest = _
            DirectCast(System.Net.WebRequest.Create("ftp://ftp.myserver.com/test.txt"), System.Net.FtpWebRequest)
        clsRequest.Credentials = New System.Net.NetworkCredential("myusername", "mypassword")
        clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
         ' read in file...
        Dim bFile() As Byte = System.IO.File.ReadAllBytes("C:\Temp\test.txt")
         ' upload file...
        Dim clsStream As System.IO.Stream = _
            clsRequest.GetRequestStream()
        clsStream.Write(bFile, 0, bFile.Length)
        clsStream.Close()
        clsStream.Dispose()

Enjoy

----------


## uri994

:wave:   :wave:  
how do i create a new directory on the server and then upload a file?
thanks

----------


## macbrutal

Thank you very much, i was suprised how it worked!
Is there anyway to DOWNLOAD a file from the Ftp? that would be awesome.

----------


## corey19981

This is JUST what I needed for my application!  it works perfect!  Thankyou very much

----------


## kake_fisk

But is it secure?

----------


## Atheist

> But is it secure?


FTP is, by default, not encrypted. So no.

----------


## kake_fisk

Okay :\
But can't you just put in clsrequest.sslenabled = true ?

----------


## Protege

"The requested URI is invalid for this FTP command."

@ line -> 

```
Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream()
```

If you could help, be great - thank you.

----------


## Atheist

How are you creating 'clsRequest'?

----------


## Protege

```
Imports System.Net
Module Module1

    Sub Main()
        Dim clsRequest As System.Net.FtpWebRequest = _
            DirectCast(System.Net.WebRequest.Create("ftp://ftp.interstudios.co.uk"), System.Net.FtpWebRequest)
        clsRequest.Credentials = New System.Net.NetworkCredential("uploadusr", "uploadpw")
        clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile

        ' read in file...
        Dim bFile() As Byte = System.IO.File.ReadAllBytes("C:\test.txt")

        ' upload file...
        Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream()
        clsStream.Write(bFile, 0, bFile.Length)
        clsStream.Close()
        clsStream.Dispose()
    End Sub

End Module
```

I haven't really changed anything as of yet.

----------


## alimoka

hi, thx for hint

i was so confused  :Mad:   :Confused:  

However, what if the server has a proxy that blocks!!!

----------


## BoilerJDawgg

I keep getting an error message on the first line which says:  "Unable to cast object of type 'System.Net.FileWebRequest' to type 'System.Net.FtpWebRequest'."   Does anyone have any idea what's causing this?  Thanks!

----------


## met0555

make sureyou have this code at the top of all codes


vb Code:
Imports System.Net

----------


## BoilerJDawgg

Yes, I have that at the top.  I also tried using fully qualified names such as:

Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("xxxxxxxxxx"),  System.Net.FtpWebRequest)

Still, no luck.  But I've seen the original code that was posted on multiple websites, so it must work.  I'm using VB.Net 2008, and I've tried it using the 2.0 and 3.5 Framework.  I'm out of ideas at this point.

----------


## sam.murley@hotmail.c

The code given in the first post works perfectly fine when running locally:

Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://ftp.website.com/Newsletters/" & DateTime.Now.ToString("MMMM-yyyy") & " Newsletter.doc"), System.Net.FtpWebRequest)
clsRequest.Credentials = New System.Net.NetworkCredential("user", "password")
clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
'read in file...

Dim bFile() As Byte = System.IO.File.ReadAllBytes(upControl.PostedFile.FileName)

'upload the file
Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream()
clsStream.Write(bFile, 0, bFile.Length)
clsStream.Close()
clsStream.Dispose()

======


However when I upload my .aspx pages and test the uploading of word documents live (domain hosted by go daddy), the file never gets posted to my Newsletters directory....

Does anyone see something I am doing wrong? 

Thanks for any help in advance.

----------


## met0555

well, it works fine with vb.net but i didn't try with asp.net

----------


## pappasman

The reason why you cannot use that in asp.net is because asp.net does not use the same functionality. I recommend using asp.net's FileUpload control. It is a hell of a lot easier.

----------


## BillyDaKid

Just a quick question about this.
Does this send the file over in binary mode?

----------


## met0555

i think you can adjust that

----------


## pappasman

The asp.net file upload control is fully customizable. If you check MSDN, under FileUpload Control, you will see a full list of Methods and all the class details.

----------


## Wayned182

This code works great for me in .Net 2005, thanks.

But is there any way to monitor upload progress?

----------


## pappasman

Simple enough, with the fileupload control, grab the filesize using, I think, fileupload(whatever the name for your control is, if it was for pics, I would 'id' it as 'fileupload_pics'. so use something like:
//
Dim filesize = fileupload_pics.filebytes
//

the .filebytes member of the fileupload control gets the filesize from the selected file. Be sure to input logic to make sure that a file was selected and exists.
From there, you want to monitor how much data is uploaded and compare. I think Javascript has native support for monitoring how much data is being uploaded. .Net does as well, but its server side and you wouldn't want to post back everytime there was an update, even via ajax as its more cumbersome and still does a partial postback regardless. The best way is to use client side code to just update. Have javascript monitor the current amount uploaded after the click event to the full file size by passing the filebytes variable to the Javascript. For the progress bar, a good idea is to create a div with, say a width of 100px and a border. Then use javascript to put in a background. You can even use a gif and use a third div and subtract that one, so you have a nice flowing animation as well, but back on track... Make the script loop through continuously, maybe, at intervals of 25-50ms. Every 1/100th % of the file that is uploaded on comparision, add 1 pixel. You can scale the div to whatever pixel width you need. I was just using a 100px div as an example.

Sound good?

----------


## Wayned182

Hi 

I did it by altering the "upload file" part of the original code to do the following:



```
            ' upload file...
            Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream()
            intChunk = bFile.Length / 100
            pbUpload.Maximum = 100
            For I As Integer = 1 To 100
                If intOffset + intChunk > bFile.Length Then intChunk = bFile.Length - intOffset
                clsStream.Write(bFile, intOffset, intChunk)
                intOffset += intChunk
                pbUpload.Value = I
            Next
            clsStream.Close()
            clsStream.Dispose()
```

Which seems to work hundreds for me.

----------


## met0555

:Smilie: , please rate if it helped :Smilie: 

thx

----------


## want a pie

I get this error when I try to run it:

The requested URI is invalid for this FTP command.

any ideas on how to fix it?

----------


## met0555

Hi, 

Can you post ur code please

----------


## want a pie

just used the code u posted

----------


## dugi2000

I put this code in my progect but when I did a little pass large files and entered the program as a whole hangs situation is not responding to end the transfer a large file. 
It was the Cshapradti the rest of the software to form2.
What should I do?
tnx`

----------


## gil_bar

hi,
I'm getting a reply from the server saying that it is entering Passive mode.
the reply is captured as an exception.
Is there a way around it?
Can I ignore the server response? can I change something in the code to make sure the server will not use passive mode? Anything else I can do?

Gil

----------


## monkey64

The code below is quite impressive and worked first time for me (thanks met0555).  
I have a simple text file which I can successfully upload to my Web Server.  However, on viewing the text either directly on the Web Server, or by viewing the source in a Web Browser, I have a double line break in place of a single one and the page goes on for ever!  The server I'm uploading to is: Apache Version:1.3.41 (Unix).

I don't have any issues when I upload with CuteFtp.  I've tried other Web Servers and run into the same problem.  Any ideas?





> this code will let you upload a file on an ftp server. working on vb.net 2005
> i hope it will help u
> 
> 
> Upload via FTP Code:
> ' set up request...
>         Dim clsRequest As System.Net.FtpWebRequest = _
>             DirectCast(System.Net.WebRequest.Create("ftp://ftp.myserver.com/test.txt"), System.Net.FtpWebRequest)
>         clsRequest.Credentials = New System.Net.NetworkCredential("myusername", "mypassword")
> ...

----------


## PENNYSTOCK

try 
clsRequest.UseBinary = false (default is true, False is for text)

----------


## monkey64

Thanks for that, but I solved the problem by creating my text file using chr(10) instead of vbnewline.  Must be something to do with ASCII character set.

----------


## eyeconeeyecone

nice post!! guyss

is there any way to upload image over internet via .net cf thru ftp??

----------


## TWDO

> nice post!! guyss
> 
> is there any way to upload image over internet via .net cf thru ftp??



Download the freeware code at www.aspDotNetSoftware.com for the application called FTP Backup. Within that source code, you can see how to upload files to a remote FTP server with ease. It even shows how to easily do it with multiple threads. You need to create an account before you can download, but it is WELL worth it. Trust me.

- Thanks
- John Johnson
- Sr. Software Engineer

----------


## AlphaKaybin

How would you add in or increase buffer size to 2048?

----------


## Amien

this scripts works perfectly .. but what if i want to upload a second file without opening en closing the FTP connection?

----------


## astalavista_thes

Hello to all,

i used the above code and i am happy to inform you that it works. But i have a problem. I want to make an application that uploads screenshots of my desktop to my server via ftp. 

This is the code i use:


```
Public Class Form1
    Dim SC As New ScreenShot.ScreenCapture
    Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("*"), System.Net.FtpWebRequest)
    Dim bFile() As Byte
    Dim clsStream As System.IO.Stream

    Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        clsRequest.Credentials = New System.Net.NetworkCredential("*", "*")
        clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        SC.CaptureScreenToFile("c:\desktop2.jpg", Imaging.ImageFormat.Jpeg)
        bFile = System.IO.File.ReadAllBytes("c:\desktop2.jpg")
        clsStream = clsRequest.GetRequestStream()
        clsStream.Write(bFile, 0, bFile.Length)
        clsStream.Close()
        clsStream.Dispose()
    End Sub
End Class
```

When i run the application and press button1 the image of my desktop is being saved to c:\desktop2.jpg and is being uploaded to the server. But when i click the button for second time (or third, or....) this error is produced at line "clsStream = clsRequest.GetRequestStream()":
"Cannot re-call BeginGetRequestStream/BeginGetResponse while a previous call is still in progress."

So i tried to make a modification and i put "clsStream = clsRequest.GetRequestStream()" out of the button1_Click() and paste it at form1_Load().

When i try to run this, it works for the first button1 click but at the second a new error comes at line "clsStream.Write(bFile, 0, bFile.Length)": Cannot access a disposed object. 

So i decided to delete the two lines that close and dispose the object (clsStream.Close(), clsStream.Dispose()). I run this again, first click everything is right, second click no error produced but although the new desktop image is being saved to c:, the file i found to my server is the old one but (almost) double in size. If i press for third time the button, the local image is refreshed but the image on server is the old one but (almost) with triple size of the original.

What's the problem? I think that i want to do an easy job but i can't. Just press the button upload an image via ftp to server. Press again the button, upload an image to server and so on.

Thank in advance,
Thanasis

----------


## mojo69

If trying this locally what gets entered in this part
DirectCast(System.Net.WebRequest.Create("ftp://ftp.myserver.com/test.txt"),

----------


## SirPereira

Hello guys,
I already known this feature, but I would like to know if there's any chance of encrypting the password, so if someone try to debug my code after it has been compiled, he cannot see the real FTP password.

Suggestions?  :Smilie:

----------


## reconrey

i get an error on this line(and I am using the code you posted):


vb Code:
Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream()

----------


## met0555

make sure you have this code at the top of all codes




```
   Imports System.Net
```

----------


## AngeloG

Sorry for the bump, but I really need this.

Your code looks good to me, but I'm just as reconray getting an error at:


VB Code:
Dim clsStream As Stream = clsRequest.GetRequestStream()

The error is: Cannot send a content-body with this verb-type.

I've got 2 imports at the top of my file:


VB Code:
Imports System.Net
Imports System.IO

Thanks.

----------


## raj.banerjee10

Hi,
i am using this code but getting error. please help 

Private Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        If txtFileName.Text <> String.Empty Then
            Dim filename As String = Me.txtFileName.Text
            Dim fileInf As New FileInfo(filename)
            'Upload(filename)
            Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create(txtUploadSvr.Text & fileInf.Name), System.Net.FtpWebRequest)
            clsRequest.Credentials = New System.Net.NetworkCredential(txtUser.Text, txtPassword.Text)
            clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile

            ' read in file...
            Dim bFile() As Byte = System.IO.File.ReadAllBytes(txtFileName.Text)

            ' upload file...
            Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream()
            clsStream.Write(bFile, 0, bFile.Length)
            clsStream.Close()
            clsStream.Dispose()
        End If
    End Sub

----------


## fredtheman

Hello,

I'm a semi-newbie and having a problem compiling the following code that I wanted to combine with the above to upload a file to an FTP server:



```
Dim server As String
server = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\My very own key", "server", Nothing)

'Constant expression is required
Const FtpFullFileName As String = "ftp://" & server & "/" & FileName

Const FullFileName As String = "C:\Temp\test.txt"

'Constant expression is required
Const FileName As String = IO.Path.GetFileName(FullFileName)
```

For some reason, VB.Net (2008 Express) complains with "Constant expression is required" when using "server" and "FullFileName".

I get the same error if using Const instead of Dim:


```
Const server As String = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\My very own key", "server", Nothing)
```

Can someone spot the error?

Thank you.

----------


## met0555

try this myb it will solve the problem 



```
Dim server As new String

My.Computer.Registry.GetValue("HKEY_CURRENT_USER\My very own key", "server", Nothing).tostring
```

----------


## fredtheman

Thanks for the tip.

----------


## Ripalot

Hi all,

for those who are interested, here is some sample (working) VB 2005 code to upload multiple files via FTP. the code includes the following extras. will check if internet connection is active, upload each file, and then move it to an archive directory. Hope this helps

Imports System
Imports System.IO
Imports System.Net
Imports System.Runtime.InteropServices
Imports System.Text
Imports OpenNETCF.Net
Imports OpenNETCF.Net.Ftp

Public Class Form1
    Public Function IsConnectionAvailable() As Boolean
        ' Returns True if connection is available 
        ' Replace www.yoursite.com with a site that
        ' is guaranteed to be online - perhaps your 
        ' corporate site, or microsoft.com
        Dim objUrl As New System.Uri("http://(FTP server address)")   ' without ()
        ' Setup WebRequest
        Dim objWebReq As System.Net.WebRequest
        objWebReq = System.Net.WebRequest.Create(objUrl)
        Dim objResp As System.Net.WebResponse
        Try
            ' Attempt to get response and return True
            objResp = objWebReq.GetResponse
            objResp.Close()
            objWebReq = Nothing
            Return True
        Catch ex As Exception
            ' Error, exit and return False
            'objResp.Close()
            objWebReq = Nothing
            Return False
        End Try

    End Function

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If IsConnectionAvailable() = True Then

            Label4.Text = "Internet connection Active"
            Label6.Text = "Uploading Files"

            '' FTP Server
            Dim sFTPServer As String = "ftp://(FTP server address)" ' without ()
            '' FTP User Account
            Dim sUserName As String = "(username)"   ' without ()
            ''FTP sPassword
            Dim sPassword As String = "(password)"    ' without ()

            For Each sFilePath As String In IO.Directory.GetFiles("c:\folder\")

                Try

                    Dim FtpRequestCreator As New FtpRequestCreator
                    WebRequest.RegisterPrefix("ftp:", FtpRequestCreator)

                    Dim oFtpWebRequest As New FtpWebRequest(New Uri(sFTPServer))
                    oFtpWebRequest.Credentials = New NetworkCredential(sUserName, sPassword)

                    ' Getting the Request stream
                    Dim oFtpRequestStream As Stream = oFtpWebRequest.GetRequestStream()

                    Dim oStreamReader As New StreamReader(oFtpRequestStream)

                    'Just ignore the result, but read it.
                    Dim oReader As String = oStreamReader.ReadToEnd

                    'Open the input file. If the file does not exist, it's an error.
                    Dim oFileStream As New FileStream(sFilePath, FileMode.Open)

                    'Create the reader for the local file data.
                    Dim oFileReader As BinaryReader = New BinaryReader(oFileStream)

                    'Opening the data connection, this must be done before we issue the command.
                    Dim oFtpResponseStream As Stream = oFtpWebRequest.GetResponse().GetResponseStream()
                    Dim oDataWriter As New BinaryWriter(oFtpResponseStream)

                    'Prepare to send commands to the server.
                    Dim cmdWriter As New StreamWriter(oFtpRequestStream)

                    'Set transfer type to IMAGE (binary).
                    cmdWriter.Write("TYPE I\r\n" & vbCrLf)
                    cmdWriter.Flush()

                    'Reading the request output
                    Dim oStreamReader2 As New StreamReader(oFtpRequestStream)
                    oReader = oStreamReader.ReadToEnd()

                    'Reading the request output
                    Dim sReader As String
                    sReader = oStreamReader2.ReadToEnd()

                    'Write the command to the request stream.
                    cmdWriter.Write("STOR " + Path.GetFileName(sFilePath) + vbCrLf)
                    cmdWriter.Flush()

                    sReader = oStreamReader2.ReadToEnd()


                    'Allocate buffer for the data, which will be written in blocks.
                    Dim bytes As Integer
                    Dim bufsize As Integer = 4096
                    Dim buffer(bufsize) As Byte

                    While True
                        bytes = oFileReader.Read(buffer, 0, bufsize)
                        oDataWriter.Write(buffer, 0, bytes)
                        If bytes <= 0 Then
                            Exit While
                        End If
                    End While

                    oFileReader.Close()
                    oFileStream.Close()
                    oDataWriter.Close()
                    oStreamReader.Close()

                    Dim foundFileInfo As New System.IO.FileInfo(sFilePath)
                    IO.File.Move(sFilePath, "C:\Folder\archive\" & foundFileInfo.Name)

                    'Label6.Text = "Uploading Complete"
                Catch ex As Exception

                    sFilePath = Nothing

                End Try

                System.Threading.Thread.Sleep(5000)

            Next
        Else
            Label4.Text = "No internet connection"
            Label6.Text = "No FTP in progress"

        End If
    End Sub
End Class

----------

