Results 1 to 13 of 13

Thread: [RESOLVED] [2005] BCL FTP example code help

  1. #1

    Thread Starter
    Lively Member technicalItch's Avatar
    Join Date
    Nov 2005
    Location
    England, UK
    Posts
    74

    Resolved [RESOLVED] [2005] BCL FTP example code help

    I'm wondering if anyone knows this. I have got the FTP example application from the Base Class Libraries code samples for VB.net, which uses the class file below to download a file from the remote ftp

    What is the function to send a file to the remote ftp? Does anyone know?

    VB Code:
    1. Imports System.IO
    2. Imports System.Net
    3. Imports System.Text
    4.  
    5. Public Class SimpleFTPClient
    6.  
    7.     Public Function Download(ByVal destinationFile As String, ByVal downloadUri As Uri) As FtpStatusCode
    8.  
    9.         Try
    10.             ' Check if the URI is and FTP site
    11.             If Not (downloadUri.Scheme = Uri.UriSchemeFtp) Then
    12.                 Throw New ArgumentException("URI is not an FTp site")
    13.             End If
    14.  
    15.             ' Set up the request
    16.             Dim ftpRequest As FtpWebRequest = CType(WebRequest.Create(downloadUri), FtpWebRequest)
    17.  
    18.             ' use the provided credentials
    19.             If Me.m_isAnonymousUser = False Then
    20.                 ftpRequest.Credentials = New NetworkCredential(Me.m_userName, Me.m_password)
    21.             End If
    22.  
    23.             ' Download a file. Look at the other methods to see all of the potential FTP features
    24.             ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile
    25.  
    26.             ' get the response object
    27.             Dim ftpResponse As FtpWebResponse = CType(ftpRequest.GetResponse, FtpWebResponse)
    28.             Dim stream As Stream = Nothing
    29.             Dim reader As StreamReader = Nothing
    30.             Dim writer As StreamWriter = Nothing
    31.  
    32.             ' get the file as a stream from the response object and write it as
    33.             ' a file stream to the local PC
    34.             Try
    35.                 stream = ftpResponse.GetResponseStream
    36.                 reader = New StreamReader(stream, Encoding.UTF8)
    37.                 writer = New StreamWriter(destinationFile, False)
    38.                 writer.Write(reader.ReadToEnd)
    39.                 Return ftpResponse.StatusCode
    40.             Finally
    41.                 ' Allways close all streams
    42.                 stream.Close()
    43.                 reader.Close()
    44.                 writer.Close()
    45.             End Try
    46.         Catch ex As Exception
    47.             Throw ex
    48.         End Try
    49.  
    50.     End Function
    51.  
    52.     Public Property UserName() As String
    53.         Get
    54.             Return Me.m_userName
    55.         End Get
    56.         Set(ByVal value As String)
    57.             Me.m_userName = value
    58.         End Set
    59.     End Property
    60.  
    61.     Public Property Password() As String
    62.         Get
    63.             Return Me.m_password
    64.         End Get
    65.         Set(ByVal value As String)
    66.             Me.m_password = value
    67.         End Set
    68.     End Property
    69.  
    70.     Public Property IsAnonymousUser() As Boolean
    71.         Get
    72.             Return Me.m_isAnonymousUser
    73.         End Get
    74.         Set(ByVal value As Boolean)
    75.             Me.m_isAnonymousUser = value
    76.         End Set
    77.     End Property
    78.  
    79.     Private m_userName As String
    80.     Private m_password As String
    81.     Private m_isAnonymousUser As Boolean
    82.  
    83. End Class

  2. #2

    Thread Starter
    Lively Member technicalItch's Avatar
    Join Date
    Nov 2005
    Location
    England, UK
    Posts
    74

    Re: [2005] BCL FTP example code help

    I'm searching all sorts of forums and endless google search results but can't find an answer to this, perhaps there isn't one then!

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [2005] BCL FTP example code help

    ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile
    The WebRequestMethods.Ftp class has a field named UploadFile too. The FtpWebRequest.GetRequestStream method is described thusly: "Retrieves the stream used to upload data to an FTP server". I'm guessing the full solution would involve those two bits of information.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  4. #4

    Thread Starter
    Lively Member technicalItch's Avatar
    Join Date
    Nov 2005
    Location
    England, UK
    Posts
    74

    Re: [2005] BCL FTP example code help

    Ah nice one jmcilhinney! I searched for WebRequestMethods.Ftp.DownloadFile and found the following code (I have changed it a bit for my needs). But it works great!

    VB Code:
    1. Public Sub Upload(ByVal source As String, ByVal target As String)
    2.         Dim credential As NetworkCredential = New NetworkCredential
    3.         credential.UserName = "helpdesk"
    4.         credential.Password = "helpdesk"
    5.         Dim request As FtpWebRequest = DirectCast(WebRequest.Create(target), FtpWebRequest)
    6.         request.Method = WebRequestMethods.Ftp.UploadFile
    7.         request.Credentials = credential
    8.         Dim reader As New FileStream(source, FileMode.Open)
    9.         Dim buffer(Convert.ToInt32(reader.Length - 1)) As Byte
    10.         reader.Read(buffer, 0, buffer.Length)
    11.         reader.Close()
    12.         request.ContentLength = buffer.Length
    13.         Dim stream As Stream = request.GetRequestStream
    14.         stream.Write(buffer, 0, buffer.Length)
    15.         stream.Close()
    16.         Dim response As FtpWebResponse = DirectCast(request.GetResponse, FtpWebResponse)
    17.         MessageBox.Show(response.StatusDescription, "File Uploaded")
    18.         response.Close()
    19.     End Sub

  5. #5
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [2005] BCL FTP example code help

    Cool. Don't forget to resolve your thread from the Thread Tools menu.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  6. #6
    PowerPoster RhinoBull's Avatar
    Join Date
    Mar 2004
    Location
    New Amsterdam
    Posts
    24,132

    Re: [RESOLVED] [2005] BCL FTP example code help

    I ahve similar logic as posted in the above reply but it trows an exception "The requested URI is invalid for this FTP Command."...
    VB Code:
    1. Dim request As FtpWebRequest = DirectCast(WebRequest.Create([B]target[/B]), FtpWebRequest)
    2.  
    3. request.Method = WebRequestMethods.Ftp.UploadFile
    4. '...
    5. Dim stream As Stream = request.GetRequestStream '<<< GetRequestStream fails
    I can't seemed to find any documentation on the subject.
    In my case target is in the following format: ftp://ftp.server.com .

    Did anybody write ftp client in vb 2005 that actually works?

    Thank you guys.

  7. #7
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [RESOLVED] [2005] BCL FTP example code help

    I just had a quick read of the documentation and it says that WeRequest.Create can handle http://, https:// and file:// by default. You need to use WebRequest.RegisterPrefix to be able to handle other protocols. RegisterPrefix requires an IWebRequestCreate object, so you'd have to define your own class that implements IWebRequestCreate. I did a quick Google for "iwebrequestcreate ftp" (without quotes) and the first page had a link to a PDF document that looked like it probably has what you're after.

    http://www.google.com.au/search?clie...=Google+Search
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  8. #8

  9. #9

  10. #10
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [RESOLVED] [2005] BCL FTP example code help

    when i wrote an ftp application i simply used:

    VB Code:
    1. My.Computer.Network.UploadFile(SourceFile, FTPadress)
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  11. #11

  12. #12
    New Member
    Join Date
    Aug 2006
    Posts
    1

    Re: [RESOLVED] [2005] BCL FTP example code help

    I sent some time on this. That one liner is pretty sweet but it seems to want to use passive which I don't allow on my server. So here is what I came up with. And RhinoBull your ftp address will work fine but you have to add the destination filename to it. This will validate the address for you.
    Hope this saves someone some time and pain. Oh yea...this is VB 2005.

    Public Function Upload(ByVal destinationFile As String, ByVal uploadUri As Uri) As FtpStatusCode
    Try
    '** Check if the URI is an FTP site
    If Not (uploadUri.Scheme = Uri.UriSchemeFtp) Then
    Throw New ArgumentException("URI is not an FTP site")
    End If

    '** Set up the request
    Dim ftpRequest As FtpWebRequest = DirectCast(WebRequest.Create(uploadUri), FtpWebRequest)
    ftpRequest.UseBinary = True
    ftpRequest.Proxy = Nothing
    ftpRequest.UsePassive = False
    ftpRequest.Timeout = 20000

    '** use the provided credentials
    If Me.m_isAnonymousUser = False Then
    ftpRequest.Credentials = New NetworkCredential(Me.m_userName, Me.m_password)
    End If

    ftpRequest.Method = WebRequestMethods.Ftp.UploadFile
    Dim requestStream As Stream = ftpRequest.GetRequestStream()

    '** get the file as a stream from the response object and write it as a file stream.
    Dim reader As New FileStream(destinationFile, FileMode.Open)
    Dim buffer(Convert.ToInt32(reader.Length - 1)) As Byte
    reader.Read(buffer, 0, buffer.Length)
    reader.Close()
    reader = New FileStream(destinationFile, FileMode.Open)
    ftpRequest.ContentLength = buffer.Length

    '** Should chunk this out out in case its big.
    buffer = New Byte(1024) {}
    Dim bytesRead As Integer
    While True
    bytesRead = reader.Read(buffer, 0, buffer.Length)
    If bytesRead = 0 Then
    Exit While
    End If
    requestStream.Write(buffer, 0, bytesRead)
    End While
    reader.Close()

    '** The request stream must be closed before getting the response.
    requestStream.Close()

    Dim response As FtpWebResponse = DirectCast(ftpRequest.GetResponse, FtpWebResponse)
    Return response.StatusCode
    response.Close()
    Catch ex As Exception
    Globals.LogError(ex)
    End Try
    End Function

    *** And the function this is called something like this...

    Dim FTPClient As SimpleFTPClient = New SimpleFTPClient

    '** This uses the Simple Client...I like this better.
    FTPClient.UserName = StaticUtils.TSTDecrypt(My.Settings.FTPUser)
    FTPClient.Password = StaticUtils.TSTDecrypt(My.Settings.FTPPass)
    FTPClient.IsAnonymousUser = False
    FTPClient.Upload(FullName, New Uri(My.Settings.FTPURL & FileName))

    Later.

  13. #13
    New Member
    Join Date
    Dec 2006
    Posts
    1

    Re: [RESOLVED] [2005] BCL FTP example code help

    jpetrie, I'm not getting this to work because my ftpRequest doesn't have members "UseBinary" nor "UsePassive". What are you using for ftpRequest?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width