Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. Imports System.Runtime.InteropServices
  2.  
  3. ''' <warning>DO NOT REMOVE ANY OF THIS INFORMATION.</warning>
  4. ''' <author>loyalty</author>
  5. ''' <link>http://loyaltyHF.blogspot.com</link>
  6. ''' <email>loyalty.exe@gmail.com</email>
  7. ''' <summary>FTP Class based on win32 APIs.
  8. ''' The default .NET methods for dealing with FTP, connect and disconnect eventualy with the operation so if
  9. ''' you are willing to do multiple operation then you'll connect and disconnect along with with every operation
  10. ''' For Example: My.Computer.Network.UploadFile</summary>
  11. ''' <remarks>Feel free to use this class but don't forget to give credits</remarks>
  12. ''' <Initial_Release>November 27,2012</Initial_Release>
  13.  
  14. Public Class FTPClass
  15.  
  16. #Region "Native"
  17.     'http://msdn.microsoft.com/en-us/library/windows/desktop/aa385473%28v=vs.85%29.aspx
  18.  
  19.     'http://pinvoke.net/default.aspx/wininet.InternetOpen
  20.    Private Declare Function InternetOpen Lib "wininet.dll" Alias "InternetOpenA" ( _
  21.     ByVal sAgent As String, _
  22.     ByVal lAccessType As Int32, _
  23.     ByVal sProxyName As String, _
  24.     ByVal sProxyBypass As String, _
  25.     ByVal lFlags As Integer) As Int32
  26.  
  27.     'http://pinvoke.net/default.aspx/wininet.InternetConnect
  28.    Private Declare Auto Function InternetConnect Lib "wininet.dll" ( _
  29.     ByVal hInternetSession As System.IntPtr, _
  30.     ByVal sServerName As String, _
  31.     ByVal nServerPort As Integer, _
  32.     ByVal sUsername As String, _
  33.     ByVal sPassword As String, _
  34.     ByVal lService As Int32, _
  35.     ByVal lFlags As Int32, _
  36.     ByVal lContext As System.IntPtr) As System.IntPtr
  37.  
  38.     'http://pinvoke.net/default.aspx/wininet.FtpPutFile
  39.    Private Declare Function FtpPutFile Lib "wininet.dll" Alias "FtpPutFileA" ( _
  40.     ByVal hFtpSession As IntPtr, _
  41.     ByVal lpszLocalFile As String, _
  42.     ByVal lpszRemoteFile As String, _
  43.     ByVal dwFlags As Integer, _
  44.     ByVal dwContext As Integer) As Boolean
  45.  
  46.     'http://pinvoke.net/default.aspx/wininet.InternetCloseHandle
  47.    Private Declare Function InternetCloseHandle Lib "wininet.dll" ( _
  48.     ByVal hInet As IntPtr) As Boolean
  49.  
  50.     'http://pinvoke.net/default.aspx/wininet.FtpCreateDirectory
  51.    <DllImport("wininet.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
  52.     Private Shared Function FtpCreateDirectory(ByVal hConnect As IntPtr, ByVal lpszDirectory As String) As Boolean
  53.     End Function
  54.  
  55.     'http://pinvoke.net/default.aspx/wininet.FtpSetCurrentDirectory
  56.    Declare Function FtpSetCurrentDirectory Lib "wininet.dll" Alias _
  57.         "FtpSetCurrentDirectoryA" _
  58.         (ByVal hConnect As IntPtr, _
  59.          ByVal lpszDirectory As String) As Boolean
  60.  
  61.     'http://www.pinvoke.net/default.aspx/wininet.InternetGetLastResponseInfo
  62.    Declare Function InternetGetLastResponseInfo Lib "wininet.dll" Alias "InternetGetLastResponseInfoA" _
  63.    (ByRef errorCode As Integer, _
  64.     ByVal buffer As String, _
  65.     ByRef bufferLength As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
  66.  
  67. #End Region
  68.  
  69. #Region "Declearions"
  70.     Public Delegate Sub Progress(ByVal name As String, ByVal Progress As Integer, ByVal msg As String)
  71.     Public Event Uploading(ByVal name As String)
  72.     Public Event Uploaded(ByVal name As String)
  73.     Public Event UploadFailed(ByVal name As String)
  74.     Public Event ServerResponce(ByVal info As String)
  75. #End Region
  76.  
  77. #Region "Properties"
  78.  
  79.     Private _connect As IntPtr
  80.     Private Property Connect() As IntPtr
  81.         Get
  82.             Return _connect
  83.         End Get
  84.         Set(ByVal value As IntPtr)
  85.             _connect = value
  86.         End Set
  87.     End Property
  88.  
  89.  
  90.     Private _hInet As IntPtr
  91.     Private Property hInet() As IntPtr
  92.         Get
  93.             Return _hInet
  94.         End Get
  95.         Set(ByVal value As IntPtr)
  96.             _hInet = value
  97.         End Set
  98.     End Property
  99.  
  100.     Private _conneted As Boolean
  101.     Public Property Connected() As Boolean
  102.         Get
  103.             Return _conneted
  104.         End Get
  105.         Set(ByVal value As Boolean)
  106.             _conneted = value
  107.         End Set
  108.     End Property
  109.  
  110.  
  111.     Private _port As Integer = 21
  112.     Private Property Port() As Integer
  113.         Get
  114.             Return _port
  115.         End Get
  116.         Set(ByVal value As Integer)
  117.             _port = value
  118.         End Set
  119.     End Property
  120.  
  121. #End Region
  122.  
  123. #Region "Consructor"
  124.     ''' <summary>
  125.    ''' Creates a new instance of FTPClass and starts a new internet session
  126.    ''' </summary>
  127.    ''' <param name="address">address/ip of the server. Don't include the protocol</param>
  128.    ''' <param name="user">Username</param>
  129.    ''' <param name="pass">Password</param>
  130.    ''' <param name="_port">Port Number. Default is 21</param>
  131.    Sub New(ByVal address As String, ByVal user As String, ByVal pass As String, Optional ByVal _port As Integer = 21)
  132.         Port = _port
  133.         OpenConnection(address, user, pass)
  134.     End Sub
  135. #End Region
  136.  
  137. #Region "Private Methods"
  138.     Private Sub OpenConnection(ByVal address As String, ByVal user As String, ByVal pass As String)
  139.         hInet = InternetOpen("Internet Explorer", 1, vbNullString, vbNullString, 0)
  140.         If hInet = 0 Then
  141.             Connected = False
  142.         Else
  143.             Connect = InternetConnect(hInet, address, Port, user, pass, 1, 0, 0)
  144.             If Connect = 0 Then
  145.                 Connected = False
  146.             Else
  147.                 Connected = True
  148.             End If
  149.         End If
  150.     End Sub
  151.    
  152.     'Private Sub CreateDirectoryStructure(ByVal dir As String)
  153.    '    If Connected Then
  154.    '        FtpCreateDirectory(Connect, dir.Substring(dir.LastIndexOf("\") + 1))
  155.    '        For Each d In IO.Directory.GetDirectories(dir, "*", IO.SearchOption.AllDirectories)
  156.    '            FtpCreateDirectory(Connect, d.Remove(0, dir.LastIndexOf("\") + 1).Replace("\", "/"))
  157.    '        Next
  158.    '    Else
  159.    '        Throw New Exception("Not connected!")
  160.    '    End If
  161.    'End Sub
  162.  
  163.     Private Sub UploadDirectoryR(ByVal Folder As String, ByVal mp As String)
  164.         If Connected Then
  165.             CreateDirectory(Folder.Substring(mp.LastIndexOf("\") + 1).Replace("\", "/"))
  166.             For Each f In IO.Directory.GetFiles(Folder)
  167.                 UploadFile(f, f.Substring(mp.LastIndexOf("\") + 1).Replace("\", "/"))
  168.             Next
  169.             For Each f In IO.Directory.GetDirectories(Folder)
  170.                 UploadDirectoryR(f, mp)
  171.             Next
  172.         End If
  173.     End Sub
  174. #End Region
  175.  
  176. #Region "Public Methods"
  177.     ''' <summary>
  178.    ''' Uploads a single file to the FTP server
  179.    ''' </summary>
  180.    ''' <param name="sourceFile">Path to local file</param>
  181.    ''' <param name="remoteFile">Path to remote file. By default file is uploaded to current directory</param>
  182.    ''' <returns>Boolean</returns>
  183.    Public Function UploadFile(ByVal sourceFile As String, Optional ByVal remoteFile As String = "") As Boolean
  184.         If Connected Then
  185.             If String.IsNullOrEmpty(remoteFile) Then remoteFile = sourceFile.Substring(sourceFile.LastIndexOf("\") + 1)
  186.             RaiseEvent Uploading(sourceFile)
  187.             If FtpPutFile(Connect, sourceFile, remoteFile, 2, 0) Then
  188.                 RaiseEvent Uploaded(sourceFile)
  189.                 RaiseEvent ServerResponce(GetLastResponse)
  190.                 Return True
  191.             Else
  192.                 RaiseEvent UploadFailed(sourceFile)
  193.                 RaiseEvent ServerResponce(GetLastResponse)
  194.                 Return False
  195.             End If
  196.         Else
  197.             Throw New Exception("Not connected!")
  198.         End If
  199.     End Function
  200.  
  201.     ''' <summary>Gets the server responce for the latest request/opeation</summary>
  202.    ''' <returns>Informtion as string</returns>
  203.    Public Function GetLastResponse() As String
  204.         Dim errorCode As Integer = 0
  205.         Dim buffSize As Integer = 0
  206.         InternetGetLastResponseInfo(errorCode, vbNullString, buffSize)
  207.         Dim message As String = Space(buffSize + 1)
  208.         InternetGetLastResponseInfo(errorCode, message, buffSize)
  209.         Return message
  210.     End Function
  211.  
  212.     ''' <summary>Closes the current internet session</summary>
  213.    ''' <returns>Boolean. Success or not.</returns>
  214.    Public Function Close() As Boolean
  215.         If Connected Then
  216.             If InternetCloseHandle(Connect) Then
  217.                 InternetCloseHandle(hInet)
  218.                 RaiseEvent ServerResponce(GetLastResponse)
  219.                 Connected = False
  220.                 Return True
  221.             Else
  222.                 RaiseEvent ServerResponce(GetLastResponse)
  223.                 Return False
  224.             End If
  225.         Else
  226.             Throw New Exception("Not connected!")
  227.         End If
  228.     End Function
  229.  
  230.     ''' <summary> Upload Multiple files to remote FTP server</summary>
  231.    ''' <param name="sourceFiles">File paths as s string array</param>
  232.    ''' <returns>No. of successfully uploaded files</returns>
  233.    Public Function UploadFiles(ByVal sourceFiles As String()) As Integer
  234.         If Connected Then
  235.             Dim count As Integer = 0
  236.             For Each F In sourceFiles
  237.                 If UploadFile(F) Then
  238.                     count += 1
  239.                 End If
  240.             Next
  241.             Return count
  242.         Else
  243.             Throw New Exception("Not connected!")
  244.         End If
  245.     End Function
  246.  
  247.     ''' <summary> Upload Multiple files to remote FTP server with reporting </summary>
  248.    ''' <param name="sourceFiles">File paths as s string array</param>
  249.    ''' <param name="ProgressE">Reports progress. Progress(ByVal name As String, ByVal Progress As Integer, ByVal msg As String)</param>
  250.    ''' <returns>No. of successfully uploaded files</returns>
  251.    Public Function UploadFiles(ByVal sourceFiles As String(), ByVal ProgressE As Progress) As Integer
  252.         If Connected Then
  253.             Dim count As Integer = 0
  254.             Dim Progress As Integer = 0
  255.             Dim PCE As Progress = ProgressE
  256.             For Each F In sourceFiles
  257.                 PCE(F, CInt((Progress / sourceFiles.Length) * 100), "Uploading")
  258.                 Progress += 1
  259.                 If UploadFile(F) Then
  260.                     count += 1
  261.                     PCE(F, CInt((Progress / sourceFiles.Length) * 100), "Uploaded")
  262.                 Else
  263.                     PCE(F, CInt((Progress / sourceFiles.Length) * 100), "Upload failed")
  264.                 End If
  265.             Next
  266.             Return count
  267.         Else
  268.             Throw New Exception("Not connected!")
  269.         End If
  270.     End Function
  271.  
  272.     'Public Sub UploadDirectory(ByVal Folder As String)
  273.    '    If Connected Then
  274.    '        CreateDirectoryStructure(Folder)
  275.    '        For Each f In IO.Directory.GetFiles(Folder, "*.*", IO.SearchOption.AllDirectories)
  276.    '            UploadFile(f, f.Remove(0, Folder.LastIndexOf("\") + 1).Replace("\", "/"))
  277.    '        Next
  278.    '    Else
  279.    '        Throw New Exception("Not connected!")
  280.    '    End If
  281.    'End Sub
  282.  
  283.     ''' <summary>Uploads a directory. Uploads all the directories within that directory too.</summary>
  284.    ''' <param name="Folder">Directory to be uploaded</param>
  285.    Public Sub UploadDirectory(ByVal Folder As String)
  286.         If Connected Then
  287.             UploadDirectoryR(Folder, Folder)
  288.             RaiseEvent ServerResponce(GetLastResponse)
  289.         Else
  290.             Throw New Exception("Not connected!")
  291.         End If
  292.     End Sub
  293.  
  294.     ''' <summary>Set the current directory of the FTP server</summary>
  295.    ''' <param name="path">Directory to set as current directory</param>
  296.    ''' <returns>Boolean. Success or not.</returns>
  297.    Public Function SetCurrentDirectory(ByVal path As String) As Boolean
  298.         If Connected Then
  299.             If FtpSetCurrentDirectory(Connect, path) Then
  300.                 RaiseEvent ServerResponce(GetLastResponse)
  301.                 Return True
  302.             Else
  303.                 RaiseEvent ServerResponce(GetLastResponse)
  304.                 Return False
  305.             End If
  306.         Else
  307.             Throw New Exception("Not connected!")
  308.         End If
  309.     End Function
  310.  
  311.     ''' <summary> Creates a directory on the FTP server </summary>
  312.    ''' <param name="dir">Directory name. Remember to use "/" instead of "\"</param>
  313.    ''' <returns>Boolean. Success or not.</returns>
  314.    Public Function CreateDirectory(ByVal dir As String) As Boolean
  315.         If Connected Then
  316.             If FtpCreateDirectory(Connect, dir) Then
  317.                 RaiseEvent ServerResponce(GetLastResponse)
  318.                 Return True
  319.             Else
  320.                 RaiseEvent ServerResponce(GetLastResponse)
  321.                 Return False
  322.             End If
  323.         Else
  324.             Throw New Exception("Not connected!")
  325.         End If
  326.     End Function
  327.  
  328. #End Region
  329.  
  330. End Class