Solved

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

Posted on 2011-03-01
3
659 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
ID: 35012552
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
ID: 35016097
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
ID: 35018199
Great answers, Thank you both
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
TimeZone, day light savings, Sql server, asp.net 6 38
Change to file doesn't show up 16 57
Access Schema 6 28
.NET Enums [Flags] & Bitwise Design Question 6 30
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
THe viewer will learn how to use NetBeans IDE 8.0 for Windows to perform CRUD operations on a MySql database.
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.

820 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