VB.NET - How to Download and Upload files using SFTP?

Asked By Prabhakaran on 24-Dec-11 02:44 AM
hi friends,

                how to download and upload the files  using SFTP in vb.net? any open source or third part .dll available with examples?


Thanks in advance......
kalpana aparnathi replied to Prabhakaran on 24-Dec-11 02:52 AM
hi,

Imports
System.IO
Imports System.Diagnostics
  
Public Class Sftp
  
  'field for storing the command for opening connections.
  Private _connect As String = ""
  
  Public Sub New(ByVal host As String, ByVal username As String, _
           ByVal password As String, Optional ByVal port As Integer = 22)
  
    'get the full path to the systems temp folder for storing
    'the WinSCP.com and WinSCP.exe files in.
    Dim tempPath As String = Path.GetTempPath
  
    'check to see if the WinSCP files are in the temp path.
    'if they are not then copy them from the resources.
    If File.Exists(tempPath & "WinSCP.com") = False Then
      File.WriteAllBytes(tempPath & "WinSCP.com", My.Resources.WinSCP)
    End If
    If File.Exists(tempPath & "WinSCP.exe") = False Then
      File.WriteAllBytes(tempPath & "WinSCP.exe", My.Resources.WinSCP1)
    End If
  
    'attempt to get the host key from the SSH server. This
    'is required to make a connection to the server without storing it
    'in the winscp.ini file.
    Dim hostKey = GetAndStoreFingerprint(host & ":" & port.ToString)
  
    'build connection string for opening ssh connections.
    'this command needs to be run before any other commands.
    _connect = "open sftp://" & username & ":" & password _
      & "@" & host & ":" & port.ToString _
      & " -hostKey=" & """" & hostKey & """"
  
  End Sub
  
  Public Function UploadFile(ByVal localFilePath As String, _
                 ByVal remoteFilePath As String) As Boolean
  
    'wrap paths in quotes.
    localFilePath = """" & localFilePath & """"
    remoteFilePath = """" & remoteFilePath & """"
  
    Try
  
      'create the required startinfo for WinSCP to run in background.
      Dim startInfo As New ProcessStartInfo
      startInfo.FileName = Path.GetTempPath & "WinSCP.com"
      startInfo.RedirectStandardInput = True
      startInfo.RedirectStandardOutput = True
      startInfo.UseShellExecute = False
      startInfo.CreateNoWindow = True
      startInfo.WindowStyle = ProcessWindowStyle.Hidden
  
      'create the process object.
      Dim process As New Process
      process.StartInfo = startInfo
      process.Start()
  
      'run the commands
      process.StandardInput.WriteLine(_connect)
      process.StandardInput.WriteLine("put " & localFilePath & " " & remoteFilePath)
      process.StandardInput.Close()
  
      'get the response
      Dim response As String = process.StandardOutput.ReadToEnd
      process.WaitForExit()
  
      'check the result.
      Dim exitCode = process.ExitCode
      If exitCode = 0 Then
        Return True
      Else
        'find out why failed.
      End If
  
  
    Catch ex As Exception
      Return False
    End Try
  
    'failed because exitCode should be 0
    Return False
  End Function
  
  Public Function DownloadFile(ByVal remoteFilePath As String, _
                 ByVal localFilePath As String) As Boolean
  
    'wrap paths in quotes.
    localFilePath = """" & localFilePath & """"
    remoteFilePath = """" & remoteFilePath & """"
  
    Try
  
      'create the required startinfo for program to run in background.
      Dim startInfo As New ProcessStartInfo
      startInfo.FileName = Path.GetTempPath & "WinSCP.com"
      startInfo.RedirectStandardInput = True
      startInfo.RedirectStandardOutput = True
      startInfo.UseShellExecute = False
      startInfo.CreateNoWindow = True
      startInfo.WindowStyle = ProcessWindowStyle.Hidden
  
      'create the process object.
      Dim process As New Process
      process.StartInfo = startInfo
      process.Start()
  
      'run the commands
      process.StandardInput.WriteLine(_connect)
      process.StandardInput.WriteLine("get " & remoteFilePath & " " & localFilePath)
      process.StandardInput.Close()
  
      'get the response
      Dim response As String = process.StandardOutput.ReadToEnd
      process.WaitForExit()
  
      'check the result.
      Dim exitCode = process.ExitCode
      If exitCode = 0 Then
        Return True
      Else
        'find out why failed.
      End If
  
    Catch ex As Exception
      Return False
    End Try
  
    'failed because exitCode should be 0
    Return False
  
  End Function
  
  Private Function GetAndStoreFingerprint(ByRef host As String) As String
    Try
  
      'attempt a connect and load the fingerprint from initial connect.
      Dim startInfo As New ProcessStartInfo
      startInfo.FileName = Path.GetTempPath & "WinSCP.com"
      startInfo.RedirectStandardInput = True
      startInfo.RedirectStandardOutput = True
      startInfo.UseShellExecute = False
      startInfo.CreateNoWindow = True
      startInfo.WindowStyle = ProcessWindowStyle.Hidden
  
      Dim process As New Process
      process.StartInfo = startInfo
      process.Start()
      process.StandardInput.WriteLine("open " & host)
      process.StandardInput.Close()
      process.WaitForExit()
  
      'read the first line from the output of the command.
      Dim response As String = process.StandardOutput.ReadLine
      Dim rsa As String = ""
  
      'loop through all lines of the output for the line containing
      'the servers fingerprint (hostkey)
      While response <> Nothing
        If response.Contains("ssh-rsa") Then
          rsa = response
          Exit While
        End If
        response = process.StandardOutput.ReadLine
      End While
  
      'return the key
      Return rsa
  
    Catch ex As Exception
    End Try
  
    'return not found
    Return ""
  
  End Function
  
End Class

http://zeusarticles.com/transfer-files-using-sftp-protocol-and-vbnet-free
Anoop S replied to Prabhakaran on 24-Dec-11 03:11 AM
Unfortunately the .NET framework currently has no built in support for using SFTP and third party class libraries can be quite costly.  You can download ->Ultimate .NET SFTP Component - SSH SFTP for C#, VB.NET & ASP.NET

http://www.atp-inc.net/component/sftp.net/

then add refernce to your project and do what you want. for eg:


' Create a new instance of the Sftp class.
Dim client As New Sftp()
 
' Connect to the SFTP server.
client.Connect("myserver")
 
' Authenticate.
client.Authenticate("user", "pass")
 
' Upload local file 'c:\test.dat' to the default remote directory.
client.UploadFile("c:\test.dat", "test.dat")
 
Dim defaultDir As String = client.GetCurrentDirectory()
Console.WriteLine(String.Format("File has been uploaded to '{0}'.", defaultDir))
 
' Upload .cs and .vb files to the current directory.
client.UploadFiles("c:\temp\*.cs;*.vb", "")
 
' Download .mp3, .wav and .jpg files from '/mydir' directory to 'c:\temp'.
client.DownloadFiles("/mydir/*.mp3,*.wav,*.jpg", "c:\temp")
 
' Upload an entire directory.
client.UploadDirectory("c:\temp", "/")
 
' Download an entire directory.
client.DownloadDirectory("myremotedir", "c:\temp")
 
' Disconnect.
client.Disconnect()
Jitendra Faye replied to Prabhakaran on 26-Dec-11 04:22 AM
Try like this-

' Create a new instance of the Sftp class.
Dim client As New Sftp()

' Connect to the SFTP server.
client.Connect("myserver")

' Authenticate.
client.Authenticate("user", "pass")

' Upload local file 'c:\test.dat' to the default remote directory.
client.UploadFile("c:\test.dat", "test.dat")

Dim defaultDir As String = client.GetCurrentDirectory()
Console.WriteLine(String.Format("File has been uploaded to '{0}'.", defaultDir))

' Upload .cs and .vb files to the current directory.
client.UploadFiles("c:\temp\*.cs;*.vb", "")

' Download .mp3, .wav and .jpg files from '/mydir' directory to 'c:\temp'.
client.DownloadFiles("/mydir/*.mp3,*.wav,*.jpg", "c:\temp")

' Upload an entire directory.
client.UploadDirectory("c:\temp", "/")

' Download an entire directory.
client.DownloadDirectory("myremotedir", "c:\temp")

' Disconnect.
client.Disconnect()


Follow this link also-
http://www.atp-inc.net/component/sftp.netcf/
Riley K replied to Prabhakaran on 26-Dec-11 07:52 AM

Before you start

Check that you have an SSH server to test, and this SSH server has SFTP subsystem enabled. Alternatively, some FTP servers support SFTP protocol. If you don't have an 
SSH server...

Install SecureBlackbox .NET (you can download it from the Download page). If you plan to run the sample on the server, please read the deployment instructions in SecureBlackbox help file.

http://zeusarticles.com/transfer-files-using-sftp-protocol-and-vbnet-free
http://www.eldos.com/sbb/sftp-net-vb-sample.php

Regards