Solved

how to ftp a file to a server using VB.Net

Posted on 2011-03-01
3
641 Views
Last Modified: 2013-11-26
I have a file with full path = "c:\myfolder\myfile.pdf"
and my ftp server is = "ftp.mydomain.com"
my ftp user id is = "mydomain.com"
my ftp password is = "myPassword"
what I need to do is to write a vb.net code to send the file from my local drive to the folder "/uploads" on my server, and if the folder does not exist I need to create it.
Please provide vb.net code.
Help please. Thanks
0
Comment
Question by:fmichail
3 Comments
 
LVL 9

Assisted Solution

by:rawinnlnx9
rawinnlnx9 earned 200 total points
Comment Utility
Your Google is a bit weak but here you go: http://www.codeproject.com/KB/IP/FtpClient.aspx (a tutorial of your question).
0
 
LVL 12

Accepted Solution

by:
Hairbrush earned 300 total points
Comment Utility
I have written this for you; I think it will do exactly what you ask...
Imports System.Net
Imports System.IO

Module Module1

    Sub Main()

        Dim PDFFile As New FileInfo("c:\myfolder\myfile.pdf")
        Dim Folder As New Uri("ftp://ftp.mydomain.com/uploads/")
        Dim Uri As New Uri(Folder, PDFFile.Name)
        Dim Credential As New NetworkCredential("mydomain.com", "myPassword")
        Dim UsePassive As Boolean = True

        CreateFolderIfDoesNotExist(Folder, Credential, UsePassive)
        Upload(PDFFile, Uri, Credential, UsePassive)

    End Sub

    Sub Upload(FileToUpload As FileInfo, ByVal Destination As Uri, ByVal Credential As NetworkCredential, ByVal UsePassive As Boolean)

        Dim ftp As FtpWebRequest = GetRequest(Destination, Credential, UsePassive)
        With ftp
            .Method = WebRequestMethods.Ftp.UploadFile
            .UseBinary = True
            .ContentLength = FileToUpload.Length
        End With

        'create byte array to store: ensure at least 1 byte!
        Const BufferSize As Integer = 2048
        Dim content(BufferSize - 1) As Byte, dataRead As Integer

        'open file for reading 
        Using fs As FileStream = FileToUpload.OpenRead()
            Try
                'open request to send
                Using rs As Stream = ftp.GetRequestStream
                    Do
                        dataRead = fs.Read(content, 0, BufferSize)
                        rs.Write(content, 0, dataRead)
                    Loop Until dataRead < BufferSize
                    rs.Close()
                End Using
            Catch ex As Exception

            Finally
                fs.Close() 'ensure file closed
            End Try

        End Using

    End Sub

    Function GetRequest(ByVal URI As Uri, ByVal Credential As NetworkCredential, ByVal UsePassive As Boolean) As FtpWebRequest

        Dim result As FtpWebRequest = CType(FtpWebRequest.Create(URI), FtpWebRequest)
        With result
            .Credentials = Credential
            .KeepAlive = False
            .UsePassive = UsePassive
        End With
        Return result

    End Function

    Function GetStringResponse(ByVal ftp As FtpWebRequest) As String
        'Get the result, streaming to a string
        Dim result As String = ""
        Using response As FtpWebResponse = CType(ftp.GetResponse, FtpWebResponse)
            Dim size As Long = response.ContentLength
            Using datastream As Stream = response.GetResponseStream
                Using sr As New StreamReader(datastream)
                    result = sr.ReadToEnd()
                    sr.Close()
                End Using
                datastream.Close()
            End Using
            response.Close()
        End Using
        Return result
    End Function

    Sub CreateFolderIfDoesNotExist(ByVal Folder As Uri, ByVal Credential As NetworkCredential, ByVal UsePassive As Boolean)
        Try
            Dim request As FtpWebRequest = GetRequest(Folder, Credential, UsePassive)
            request.Method = WebRequestMethods.Ftp.ListDirectory
            Using response As FtpWebResponse = CType(request.GetResponse(), FtpWebResponse)
                Exit Sub 'Folder exists 
            End Using
        Catch ex As WebException
            If Not ex.Response Is Nothing Then
                Dim response As FtpWebResponse = CType(ex.Response, FtpWebResponse)
                If response.StatusCode = FtpStatusCode.ActionNotTakenFileUnavailable Then
                    'Folder does not exist, so create it
                    Dim ftp As FtpWebRequest = GetRequest(Folder, Credential, UsePassive)
                    ftp.Method = WebRequestMethods.Ftp.MakeDirectory

                    Try
                        'get response but ignore it
                        Dim str As String = GetStringResponse(ftp)
                    Catch ex2 As Exception
                        Throw
                    End Try
                End If
            End If
        End Try
    End Sub

End Module

Open in new window

0
 

Author Closing Comment

by:fmichail
Comment Utility
Great answers, Thank you both
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now