Upload File via FTP

Arokh

Well-known member
Joined
Apr 11, 2006
Messages
124
Upload File via FTP (URI is invalid for this FTP command)

I just wanted to upload a file to a WebServer (on which I have full access) with my program,
I didnt expect it would be so bothersome.
I finally decided to use FTP for this action, but I have run into some problems:

Im using the example from http://msdn2.microsoft.com/en-us/library/ms229715.aspx
Converted into VB.NET


[VB]
Imports System
Imports System.IO
Imports System.Net
Imports System.Text
...
Dim FTPCon As FtpWebRequest
FTPCon = WebRequest.Create("ftp://[HOST]:2100")
FTPCon.Method = WebRequestMethods.Ftp.UploadFile
FTPCon.Credentials = New NetworkCredential("[USERNAME]", "[PASSWORD]")
Dim FileContent() As Byte = Encoding.Unicode.GetBytes("Test.txt")
FTPCon.ContentLength = FileContent.Length

Dim ReqStream As Stream = FTPCon.GetRequestStream
ReqStream.Write(FileContent, 0, FileContent.Length)
ReqStream.Close()

Dim FTPRes As FtpWebResponse = FTPCon.GetResponse

If FTPRes.StatusCode = FtpStatusCode.FileActionOK Then
Return True
Else
Return False
End If[/VB]

But as soon as the program reaches FTPCon.GetRequestStream it throws the error:
A first chance exception of type System.Net.WebException occurred in System.dll
The requested URI is invalid for this FTP command.

Ive checked if the FTP Server is running with a FTP Client and there it works fine.

EDIT:
The WebServer is within my LAN, I dont know if thats important.
 
Last edited by a moderator:
Re: Upload File via FTP (URI is invalid for this FTP command)

What version of .Net are you using? Also how is the variable FTPCon declared / defined?
 
Oh I missed the first line, it is declared like this:
[VB]Dim FTPCon As FtpWebRequest[/VB]

With:
[VB]Imports System
Imports System.IO
Imports System.Net
Imports System.Text[/VB]

And Im using .Net 2.0.

(I also edited the first post)
 
I guess it was a little late while I was trying.
I had the impression WebRequest.Create would just open a connection to the FTPServer,
but it also has to point to the file to which it should be uploaded.

I should have noticed ealier since my code doesnt tell
the FTP Server to which file it should upload. :rolleyes:

My new code:
Code:
        Public Shared Function TextUpload(ByVal Host As String, ByVal Port As UInt16, ByVal UserName As String, ByVal Password As String, ByVal SourceStr As String, ByVal FileName As String) As Boolean
            Dim FTPCon As FtpWebRequest

            FTPCon = WebRequest.Create(Host & ":" & Port & "/" & FileName)
            FTPCon.Method = WebRequestMethods.Ftp.UploadFile
            FTPCon.Credentials = New NetworkCredential(UserName, Password)

            Dim FileContent() As Byte = Encoding.ASCII.GetBytes(SourceStr)
            FTPCon.ContentLength = FileContent.Length
            Try
                Dim ReqStream As Stream = FTPCon.GetRequestStream
                ReqStream.Write(FileContent, 0, FileContent.Length)
                ReqStream.Close()

                Dim FTPRes As FtpWebResponse = FTPCon.GetResponse

                Return True

            Catch ex As Exception
                Return False
            End Try
        End Function
 
Me again
Now I have another Problem:

Everything worked just fine when I call the function with the LAN IP address,
but as soon I use my dyndns.org address it fails.
It throws this error:
The server returned an address in response to the PASV command that is different than the address to which the FTP connection was made.

I had also my friend test that part of my program and has gotten the same error.

If you want to try it out yourself here is an UserAccount you can use for testing:
FTP-URL: ftp://arokh.dnsalias.org:2100
AccName: Guests
Password: Guests
(Ill leave this account open for some days)
 
Are there any firewalls or proxy servers between the internet and the FTP server? If so they will need to be configured to allow traffic in through port 2100 as well.
 
The only thing I have between my PC and Internet is a router and the port 2100 is forwarded.

It seems my program has nothing to do with the error I keep getting,
because I asked a friend to connect to my FTP-Server with a regular FTP-Client
and it didnt work either (tried both normal and passive connection).

How I set my FTP-Server up:
I have 4 PCs connected in my LAN and all of them are directly connected to the router.
I have no additional Firewall installed and the Windows-Firewall is disabled.
The FTP-Server software (Filezilla) is set to listen to port 2100.

The router has the IP address 192.168.1.1,
my PC on which I use has 192.168.1.2,
and the PC which acts as a fileserver and for serverapplications like FTP has 192.168.1.4

Now I have forwarded the Port 2100 (TCP Inbound) to the Server-PC,
no rules for Outbound Traffic are set (only the default which is to allow every Outbound traffic).

Since I have a dynamic IP I use dyndns.org to let others access my Internet-IP ( arokh.dnsalias.org ), which is updated by my router.

Passive Connection Settings in the FTP-Server:
[Broken External Image]:http://arokh.dnsalias.org/Images/Passive.png
Ive also forwarded ports 2101-2110 (TCP Inbound) to the Server but that didnt help either.

Is there something Im missing here?

The Account is still open:
FTP-URL: ftp://arokh.dnsalias.org:2100
AccName: Guests
Password: Guests
 
Ok, the FTP-Server is now up and running and others have been able to connect and upload/download files successfully, but only with regular FTP-Clients.

I still get the same error when I try to upload a file with my program.
The FTP-Server creates the file but with no content in it,
after that my program throws the error:
In Passiv Mode (FTPCon.UsePassive = True):
The server returned an address in response to the PASV command that is different than the address to which the FTP connection was made.

In Normal Mode (FTPCon.UsePassive = False):
The data connection was made from an address that is different than the address to which the FTP connection was made.
 
Been a while since I did anything programatically with FTP so I could be talking nonsense here...

I think you will need to take the response to the PASV command and open another FTP connection to the server using the new information - if you still have the ftp server running PM me and Ill try to see if I can get it working tonight.
 
Try the following code, it has worked for me recently:
Code:
 Allow a file to be uploaded to a web server using FTP.
    Public Shared Function uploadFileUsingFTP(ByVal CompleteFTPPath As String, ByVal CompleteLocalPath As String, Optional ByVal UName As String = "", Optional ByVal PWD As String = "") As String
        uploadFileUsingFTP = Nothing

        Dim resultMsg As String = "Upload complete"
        Try
            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 System.IO.FileStream = System.IO.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

            Return resultMsg

        Catch ex As Exception
            resultMsg = ex.Message
        End Try
    End Function

Code:
myFtp.uploadFileUsingFTP("ftp://yahoo.com/abc/about.txt", _
                                            System.IO.Path.GetFullPath(FileUpload1.FileName).ToString, _
                                                "username", "password")

The first parameter that you pass is the target location and the new file name.

Mike55.
 
Back
Top