user1757913
user1757913

Reputation: 53

vb.net FTP - works in some cases

i currently have this code as my FTP code (Which works a charm!)

 Using ms As New System.IO.MemoryStream
                test.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
                Using wc As New System.Net.WebClient
                    wc.UploadData("ftp://" & My.Settings.username & ":" & My.Settings.password & "@ftp." & My.Settings.server & My.Settings.imagelocation & filename & ".jpg", ms.ToArray())

                End Using
            End Using

however i have a new username and directory etc, and they contain "@" this is my username for example: "[email protected]"

but my username before would be for instance "test" you see without the "@" im guessing its because it messes with the "@ftp" part, Any suggestions how to fix?

Upvotes: 0

Views: 134

Answers (2)

Polly Shaw
Polly Shaw

Reputation: 3222

Short answer:

Encode your username and password using System.Web.HttpUtility.UrlPathEncode before creating your URL.

Long answer:

According to the IETF's RFC 1738, which is a standards track document about URLs, it explicitly says

Within the user and password field, any ":", "@", or "/" must be encoded.

The actual URL spec document does not explicitly mention encoding special characters in usernames and passwords, but I think it's implied that you can encode them. And it says

Because a % sign always indicates an encoded character, a URL may be made safer simply by encoding any characters considered unsafe, while leaving already encoded.

So you should percent-escape any special charaters in your URL, and in the case of an '@' that's %40.

Upvotes: 1

user2588578
user2588578

Reputation: 58

Alternatively you could use the following classes provided by .net:

  • FtpWebRequest
  • WebRequestMethods
  • NetworkCredential

            Private Shared Sub UploadFileToFTP(source As String)
            Try
                    Dim filename As String = Path.GetFileName(source)
                    Dim ftpfullpath As String = ftpurl
                    Dim ftp As FtpWebRequest = DirectCast(FtpWebRequest.Create(ftpfullpath), FtpWebRequest)
                    ftp.Credentials = New NetworkCredential(ftpusername, ftppassword)
    
                   ftp.KeepAlive = True
                   ftp.UseBinary = True
                   ftp.Method = WebRequestMethods.Ftp.UploadFile
    
                   Dim fs As FileStream = File.OpenRead(source)
                   Dim buffer As Byte() = New Byte(fs.Length - 1) {}
                   fs.Read(buffer, 0, buffer.Length)
                   fs.Close()
    
                   Dim ftpstream As Stream = ftp.GetRequestStream()
                   ftpstream.Write(buffer, 0, buffer.Length)
                   ftpstream.Close()
            Catch ex As Exception
                     Throw ex
            End Try
            End Sub
    

Upvotes: 0

Related Questions