Example #1
0
        public static bool downloadSecureFile(Uri serverUri, string filename, string username, string password, bool UseSSL, string destFile)
        {
            // The serverUri parameter should use the ftp:// scheme.
            // It contains the name of the server file that is to be deleted.
            // Example: ftp://contoso.com/someFile.txt.
            //
            if (serverUri.Scheme != Uri.UriSchemeFtp) {
                return false;
            }

            Sftp sftp = new Sftp(serverUri.Host, username, password);
            if (sftp == null) {
                //Error connecting to FTP server
                throw new WebException("ERROR - " + ClassName + ": Error connecting to FTP server", WebExceptionStatus.SecureChannelFailure);
            } else {

                try {
                    sftp.OnTransferStart += new FileTransferEvent(sftp_OnTransferStart);
                    sftp.OnTransferProgress += new FileTransferEvent(sftp_OnTransferProgress);
                    sftp.OnTransferEnd += new FileTransferEvent(sftp_OnTransferEnd);
                    sftp.Connect();
                    sftp.Get(serverUri.LocalPath + filename, destFile);

                    //confirm the file is fully downloaded
                    long remoteSize = sftp.getSize(serverUri.LocalPath + filename);
                    FileInfo localfile = new FileInfo(destFile);
                    long localSize = localfile.Length;

                    if (localSize >= (remoteSize - 100)) {
                        return true;
                    } else {
                        //file was not complete
                        return false;
                    }

                } catch (Tamir.SharpSsh.jsch.SftpException sfex) {
                    // write to log - note the lowercase m in message - this library uses nonstandard error reporting
                    Trace.TraceInformation("ERROR - " + ClassName + ":" + sfex.message);
                    throw new WebException("ERROR - " + ClassName + ": " + sfex.message);

                } catch (Exception ex) {
                    // write to log
                    Trace.TraceInformation("ERROR - " + ClassName + ":" + ex.Message);
                    //EventLog.WriteEntry(Application.ProductName, "ERROR - " + ClassName + ":" + ex.Message, EventLogEntryType.Error);
                    throw new WebException("ERROR - " + ClassName + ": " + ex.Message);
                    //return false;

                } finally {
                    sftp.Close();
                }
            }
        }