Wednesday, 15 August 2012

VB.NET - FTP - Check if directory exists and upload file

        Dim localFolderAndFile As String = "C:\Temp\fileName.pdf"
        Dim remoteFolder As String = "/Test3/"
        Dim remoteFolderAndFile As String = "/Test3/fileName.pdf"
        Dim host As String = "ftp://hostname.com"
        Dim username As String = "UserName"
        Dim password As String = "Password"

        Dim fwrRequest As System.Net.FtpWebRequest
        Dim fwrResponse As System.Net.WebResponse
        Try
            fwrRequest = DirectCast(System.Net.WebRequest.Create(host & remoteFolder), System.Net.FtpWebRequest)
            fwrRequest.Credentials = New System.Net.NetworkCredential(username, password)

            fwrRequest.Method = System.Net.WebRequestMethods.Ftp.MakeDirectory

            fwrResponse = fwrRequest.GetResponse
        Catch ex As Exception
            ' already exists
        End Try

        ' upload file
        fwrRequest = DirectCast(System.Net.WebRequest.Create(host & remoteFolderAndFile), System.Net.FtpWebRequest)
        fwrRequest.Credentials = New System.Net.NetworkCredential(username, password)
        fwrRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
        Dim bFile() As Byte = System.IO.File.ReadAllBytes(localFolderAndFile)
        Dim ioStream As System.IO.Stream = fwrRequest.GetRequestStream()
        ioStream.Write(bFile, 0, bFile.Length)
        ioStream.Close()
        ioStream.Dispose()

2 comments:

  1. Thanks, I tried many ways, but your code works perfectly.

    ReplyDelete
  2. After 4 years the code works. Thanks

    ReplyDelete