INTERNET APPLICATION DEVELOPMENT
MID MARKET ERP DEVELOPMENT
by Jacky Xu
Sometimes we have project where we need to connect to an sftp server, download and upload a file. But, Microsoft .net library does not have an easy solution for it. WinSCP provides a .net library to operate the sftp site easily.
1. You should download the library from WinSCP website and install it.
2. Add it to your project’s reference.
3. Add a method to open a session to connect to sftp server.
The sftp session needs a parameter “SshHostKeyFingerprint”. For the first time you connect, we don’t have a value. When you connect to sftp server, the code will go through an exception. Then we can use the exception information to get the value of the parameter. Note, you should store the value to a setting file after you get the value and you can use it when the program opens the session next time. In my sample code, the program will open a session again based on the value of the parameter.
1. After the session opens, you can upload, download and delete the file from sftp server.
Upload File:
Download File:
Delete File:
That’s it. It's much easier than I thought it would be.
I checked the link about "Where do I get SSH host key fingerprint for use with scripting or .NET assembly?". I want to use WinSCP with security. But sometimes I cannot get the key from the client. So I add the exception handler to get the key and save it to the configuration file in setup UI. When the main program is running, the program will get the key from the configuration file and use the key to connect to sftp server. If there is any error for main program it will show the error. Thanks for your post.
Thanks. I will check it.
You should never automatically accept an SSH host key. You loose any security by doing so. Verifying the SSH host key is a crucial security feature. See <a href="http://winscp.net/eng/docs/ssh_verifying_the_host_key">Verifying the Host Key</a> and also <a href="http://winscp.net/eng/docs/faq_script_hostkey">Where do I get SSH host key fingerprint for use with scripting or .NET assembly?</a>.If you really do not care about security, use <a href="http://winscp.net/eng/docs/library_sessionoptions">SessionOptions.GiveUpSecurityAndAcceptAnySshHostKey</a>.