Wednesday, March 14, 2012

FTP Utility

Imports System.IO
Imports System.Net

Public Class FTP

    'Variaveis com o mesmo nome do XML!
    Private Caminho As String
    Private Objeto As String
    Private CaminhoFTP As String
    'Fim Variaveis com o mesmo nome do XML!


    Private ftpIP As String = "www.xpto.com.br"
    Private ftpUsuario As String = "ftp"
    Private ftpSenha As String = "ftp@123"

    Private Sub EnviarDiretorio()
        Dim f As File
        Dim d As New DirectoryInfo(Caminho)
        Dim i As Integer
        Dim infoArquivo As FileInfo
        Dim dt As New DataTable("Resumo")
        Dim dr As DataRow
        Dim caminhoxml As String = Objeto + "_" + Guid.NewGuid.ToString + ".xml"

        dt.Columns.Add("Arquivo")
        dt.Columns.Add("Tamanho")
        dt.Columns.Add("Data")
        dt.Columns.Add("OK")
        Try
            ProgressBar1.Minimum = 1
            ProgressBar1.Maximum = d.GetFiles.Length + 1
            ProgressBar1.Value = 1

            Try


                For Each infoArquivo In d.GetFiles
                    If infoArquivo.LastWriteTime.Date.ToString("yyyyMMdd") = dtImp.Value.Date.ToString("yyyyMMdd") Then
                        dr = dt.NewRow()
                        dr.Item("Arquivo") = infoArquivo.Name
                        dr.Item("Tamanho") = infoArquivo.Length
                        dr.Item("Data") = Now.ToString
                        ftpEnviar(infoArquivo.FullName)
                        dr.Item("OK") = True
                        dt.Rows.Add(dr)
                    End If
                    ProgressBar1.Value += 1
                Next

            Catch ex As Exception
                dr.Item("OK") = False
                dt.Rows.Add(dr)
            End Try


            dt.WriteXml(caminhoxml)
            ftpEnviar(caminhoxml)
            File.Delete(caminhoxml)

            MsgBox("Arquivos enviados para o Servidor!")

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try


    End Sub
    ' metod enviar
    Private Sub ftpEnviar(ByVal nomeArq As String)


        Dim buffLength As Integer = 2048
        Dim buff(buffLength) As Byte

        Dim infoArquivo As FileInfo
        Dim conteudoLen As Integer
        Dim uriPath As String = "ftp://" + ftpIP + "/" + CaminhoFTP + "/" + Objeto + "/" + dtImp.Value.Date.ToString("yyyyMMdd") + "/"
        Dim reqFTP As FtpWebRequest
        Dim strm As Stream


        Try
            Try
                If Not WebRequestMethods.Ftp.ListDirectoryDetails.Contains("ftp://" + ftpIP + "/" + CaminhoFTP + "/" + Objeto + "/") Then
                    reqFTP = CType(WebRequest.Create("ftp://" + ftpIP + "/" + CaminhoFTP + "/" + Objeto + "/"), FtpWebRequest)
                    reqFTP.Credentials = New NetworkCredential(ftpUsuario, ftpSenha)
                    reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory
                    Dim FTPRes As FtpWebResponse
                    FTPRes = CType(reqFTP.GetResponse, FtpWebResponse)
                End If

            Catch ex As Exception

            End Try
            Try


                If Not WebRequestMethods.Ftp.ListDirectoryDetails.Contains(uriPath) Then
                    reqFTP = CType(WebRequest.Create(uriPath), FtpWebRequest)
                    reqFTP.Credentials = New NetworkCredential(ftpUsuario, ftpSenha)
                    reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory
                    Dim FTPRes As FtpWebResponse
                    FTPRes = CType(reqFTP.GetResponse, FtpWebResponse)
                End If

            Catch ex As Exception

            End Try

            infoArquivo = New FileInfo(nomeArq)
            reqFTP = FtpWebRequest.Create(New Uri(uriPath + infoArquivo.Name))
            reqFTP.Credentials = New NetworkCredential(ftpUsuario, ftpSenha)
            reqFTP.KeepAlive = False
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile
            reqFTP.UseBinary = True
            reqFTP.ContentLength = infoArquivo.Length

            Dim fs As FileStream = infoArquivo.OpenRead()
            Try


                strm = reqFTP.GetRequestStream()
                conteudoLen = fs.Read(buff, 0, buffLength)
                Do While (conteudoLen <> 0)

                    strm.Write(buff, 0, conteudoLen)
                    conteudoLen = fs.Read(buff, 0, buffLength)
                Loop

                strm.Close()
                fs.Close()

            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub ftpReceber(ByVal localArq As String, ByVal nomeArq As String)

        Dim reqFTP As FtpWebRequest
        Dim bufferSize As Integer = 2048
        Dim Buffer(bufferSize) As Byte

        Try


            Dim outputStream As New FileStream(localArq + "\\" + nomeArq, FileMode.Create)
            reqFTP = FtpWebRequest.Create(New Uri("ftp://" + ftpIP + "/" + nomeArq))
            reqFTP.Method = WebRequestMethods.Ftp.DownloadFile
            reqFTP.UseBinary = True
            reqFTP.Credentials = New NetworkCredential(ftpUsuario, ftpSenha)
            Dim response As FtpWebResponse = reqFTP.GetResponse()
            Dim ftpStream As Stream = response.GetResponseStream()
            Dim cl As Long = response.ContentLength

            Dim readCount As Integer

            readCount = ftpStream.Read(Buffer, 0, bufferSize)
            Do While (readCount > 0)

                outputStream.Write(Buffer, 0, readCount)
                readCount = ftpStream.Read(Buffer, 0, bufferSize)
            Loop

            ftpStream.Close()
            outputStream.Close()
            response.Close()

        Catch ex As Exception
            MessageBox.Show(ex.Message)

        End Try
    End Sub

    Private Sub FTP_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim obj As New DataSet
        Dim dt As DataTable
        Try

            dtImp.Value = Now

            obj.ReadXml("config.xml")

            dt = obj.Tables(0)

            If dt.Rows.Count > 0 Then
                Objeto = dt.Rows(0).Item("Objeto").ToString()
                If System.IO.Directory.Exists(dt.Rows(0).Item("Caminho").ToString()) Then
                    Caminho = dt.Rows(0).Item("Caminho").ToString()
                Else
                    Caminho = "Caminho não encontrado."
                End If
                CaminhoFTP = dt.Rows(0).Item("CaminhoFTP").ToString()

            End If

            lblCaminho.Text = Caminho
            lblObjeto.Text = Objeto

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub btnEnviar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnviar.Click
        Try
            If Not System.IO.Directory.Exists(Caminho) Then
                MsgBox("Caminho não encontrado.")
                Exit Sub
            End If
            EnviarDiretorio()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
End Class

No comments: