9 people like it.

FTPS download and upload a file

FTPS = SSL encrypted FTP. SFTP = FTP over SSH.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
41: 
42: 
43: 
44: 
45: 
46: 
47: 
48: 
49: 
50: 
51: 
52: 
53: 
54: 
55: 
56: 
57: 
58: 
// Get from the server certificate. Set this as config, as the server may change the certificate.
let ``trusted server certificate hash`` = "603780E732DB12D0F6BA434BA8E04D141904A165"

open System
open System.IO
open System.Net
open System.Net.Security

type FTPSClient(username:string, password:string) =
    inherit WebClient(Credentials =
        (NetworkCredential(username.Normalize(), password.Normalize()) :> ICredentials),
         UseDefaultCredentials = false)
    override __.GetWebRequest(address) =
        let request = base.GetWebRequest(address) :?> FtpWebRequest
        request.Credentials <- NetworkCredential(username.Normalize(), password.Normalize())
        request.EnableSsl <- true
        request.UsePassive <- true
        //request.UseBinary <- t
        ServicePointManager.ServerCertificateValidationCallback <-
            RemoteCertificateValidationCallback(
                fun obj serverCert chain errors ->
                    // Validate server security certificate here!
                    if serverCert.GetCertHashString() = ``trusted server certificate hash`` then
                        true
                    else
                    match errors with
                    | SslPolicyErrors.None -> true
                    | x -> Console.WriteLine("Server SSL invalid: " +
                                Enum.GetName(typeof<SslPolicyErrors>, (box x)))
                           false)
        let cert =
            request.ClientCertificates.Add(
                new System.Security.Cryptography.X509Certificates.X509Certificate())
        request :> WebRequest

let downloadFTPS host username (password:string) fileName targetPath =
    async {
        use client = new FTPSClient(username, password)
        let fileToGet = Uri("ftp://" + host + "/" + fileName)
        let target = Path.Combine [| targetPath; fileName |]
        return! client.DownloadFileTaskAsync(fileToGet, target) |> Async.AwaitTask
    }

let uploadFTPS host username (password:string) filePath =
    async {
        let fileName = Path.GetFileName(filePath)
        use client = new FTPSClient(username, password)
        let fileToSend = Uri("ftp://" + host + "/" + fileName)
        return!
            client.UploadFileTaskAsync(fileToSend, WebRequestMethods.Ftp.UploadFile, filePath)
            |> Async.AwaitTask |> Async.Catch
    }

//downloadFTPS "test.rebex.net" "demo" "password" "readme.txt" @"c:\temp\"
//|> Async.RunSynchronously

//uploadFTPS "test.rebex.net" "demo" "password" @"C:\Temp\test3.txt"
//|> Async.RunSynchronously
val ( trusted server certificate hash ) : string

Full name: Script.( trusted server certificate hash )
namespace System
namespace System.IO
namespace System.Net
namespace System.Net.Security
Multiple items
type FTPSClient =
  inherit WebClient
  new : username:string * password:string -> FTPSClient
  override GetWebRequest : address:Uri -> WebRequest

Full name: Script.FTPSClient

--------------------
new : username:string * password:string -> FTPSClient
val username : string
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = String

Full name: Microsoft.FSharp.Core.string
val password : string
Multiple items
type WebClient =
  inherit Component
  new : unit -> WebClient
  member BaseAddress : string with get, set
  member CachePolicy : RequestCachePolicy with get, set
  member CancelAsync : unit -> unit
  member Credentials : ICredentials with get, set
  member DownloadData : address:string -> byte[] + 1 overload
  member DownloadDataAsync : address:Uri -> unit + 1 overload
  member DownloadFile : address:string * fileName:string -> unit + 1 overload
  member DownloadFileAsync : address:Uri * fileName:string -> unit + 1 overload
  member DownloadString : address:string -> string + 1 overload
  ...

Full name: System.Net.WebClient

--------------------
WebClient() : unit
Multiple items
type NetworkCredential =
  new : unit -> NetworkCredential + 4 overloads
  member Domain : string with get, set
  member GetCredential : uri:Uri * authType:string -> NetworkCredential + 1 overload
  member Password : string with get, set
  member SecurePassword : SecureString with get, set
  member UserName : string with get, set

Full name: System.Net.NetworkCredential

--------------------
NetworkCredential() : unit
NetworkCredential(userName: string, password: string) : unit
NetworkCredential(userName: string, password: Security.SecureString) : unit
NetworkCredential(userName: string, password: string, domain: string) : unit
NetworkCredential(userName: string, password: Security.SecureString, domain: string) : unit
type ICredentials =
  member GetCredential : uri:Uri * authType:string -> NetworkCredential

Full name: System.Net.ICredentials
override FTPSClient.GetWebRequest : address:Uri -> WebRequest

Full name: Script.FTPSClient.GetWebRequest
val address : Uri
val request : FtpWebRequest
type FtpWebRequest =
  inherit WebRequest
  member Abort : unit -> unit
  member BeginGetRequestStream : callback:AsyncCallback * state:obj -> IAsyncResult
  member BeginGetResponse : callback:AsyncCallback * state:obj -> IAsyncResult
  member ClientCertificates : X509CertificateCollection with get, set
  member ConnectionGroupName : string with get, set
  member ContentLength : int64 with get, set
  member ContentOffset : int64 with get, set
  member ContentType : string with get, set
  member Credentials : ICredentials with get, set
  member EnableSsl : bool with get, set
  ...

Full name: System.Net.FtpWebRequest
property FtpWebRequest.Credentials: ICredentials
String.Normalize() : string
String.Normalize(normalizationForm: Text.NormalizationForm) : string
property FtpWebRequest.EnableSsl: bool
property FtpWebRequest.UsePassive: bool
type ServicePointManager =
  static val DefaultNonPersistentConnectionLimit : int
  static val DefaultPersistentConnectionLimit : int
  static member CertificatePolicy : ICertificatePolicy with get, set
  static member CheckCertificateRevocationList : bool with get, set
  static member DefaultConnectionLimit : int with get, set
  static member DnsRefreshTimeout : int with get, set
  static member EnableDnsRoundRobin : bool with get, set
  static member EncryptionPolicy : EncryptionPolicy
  static member Expect100Continue : bool with get, set
  static member FindServicePoint : address:Uri -> ServicePoint + 2 overloads
  ...

Full name: System.Net.ServicePointManager
property ServicePointManager.ServerCertificateValidationCallback: RemoteCertificateValidationCallback
type RemoteCertificateValidationCallback =
  delegate of obj * X509Certificate * X509Chain * SslPolicyErrors -> bool

Full name: System.Net.Security.RemoteCertificateValidationCallback
Multiple items
val obj : obj

--------------------
type obj = Object

Full name: Microsoft.FSharp.Core.obj
val serverCert : Security.Cryptography.X509Certificates.X509Certificate
val chain : Security.Cryptography.X509Certificates.X509Chain
val errors : SslPolicyErrors
Security.Cryptography.X509Certificates.X509Certificate.GetCertHashString() : string
type SslPolicyErrors =
  | None = 0
  | RemoteCertificateNotAvailable = 1
  | RemoteCertificateNameMismatch = 2
  | RemoteCertificateChainErrors = 4

Full name: System.Net.Security.SslPolicyErrors
field SslPolicyErrors.None = 0
val x : SslPolicyErrors
type Console =
  static member BackgroundColor : ConsoleColor with get, set
  static member Beep : unit -> unit + 1 overload
  static member BufferHeight : int with get, set
  static member BufferWidth : int with get, set
  static member CapsLock : bool
  static member Clear : unit -> unit
  static member CursorLeft : int with get, set
  static member CursorSize : int with get, set
  static member CursorTop : int with get, set
  static member CursorVisible : bool with get, set
  ...

Full name: System.Console
Console.WriteLine() : unit
   (+0 other overloads)
Console.WriteLine(value: string) : unit
   (+0 other overloads)
Console.WriteLine(value: obj) : unit
   (+0 other overloads)
Console.WriteLine(value: uint64) : unit
   (+0 other overloads)
Console.WriteLine(value: int64) : unit
   (+0 other overloads)
Console.WriteLine(value: uint32) : unit
   (+0 other overloads)
Console.WriteLine(value: int) : unit
   (+0 other overloads)
Console.WriteLine(value: float32) : unit
   (+0 other overloads)
Console.WriteLine(value: float) : unit
   (+0 other overloads)
Console.WriteLine(value: decimal) : unit
   (+0 other overloads)
type Enum =
  member CompareTo : target:obj -> int
  member Equals : obj:obj -> bool
  member GetHashCode : unit -> int
  member GetTypeCode : unit -> TypeCode
  member HasFlag : flag:Enum -> bool
  member ToString : unit -> string + 3 overloads
  static member Format : enumType:Type * value:obj * format:string -> string
  static member GetName : enumType:Type * value:obj -> string
  static member GetNames : enumType:Type -> string[]
  static member GetUnderlyingType : enumType:Type -> Type
  ...

Full name: System.Enum
Enum.GetName(enumType: Type, value: obj) : string
val typeof<'T> : Type

Full name: Microsoft.FSharp.Core.Operators.typeof
val box : value:'T -> obj

Full name: Microsoft.FSharp.Core.Operators.box
val cert : int
property FtpWebRequest.ClientCertificates: Security.Cryptography.X509Certificates.X509CertificateCollection
Security.Cryptography.X509Certificates.X509CertificateCollection.Add(value: Security.Cryptography.X509Certificates.X509Certificate) : int
namespace System.Security
namespace System.Security.Cryptography
namespace System.Security.Cryptography.X509Certificates
Multiple items
type X509Certificate =
  new : unit -> X509Certificate + 13 overloads
  member Equals : obj:obj -> bool + 1 overload
  member Export : contentType:X509ContentType -> byte[] + 2 overloads
  member GetCertHash : unit -> byte[]
  member GetCertHashString : unit -> string
  member GetEffectiveDateString : unit -> string
  member GetExpirationDateString : unit -> string
  member GetFormat : unit -> string
  member GetHashCode : unit -> int
  member GetIssuerName : unit -> string
  ...

Full name: System.Security.Cryptography.X509Certificates.X509Certificate

--------------------
Security.Cryptography.X509Certificates.X509Certificate() : unit
   (+0 other overloads)
Security.Cryptography.X509Certificates.X509Certificate(data: byte []) : unit
   (+0 other overloads)
Security.Cryptography.X509Certificates.X509Certificate(fileName: string) : unit
   (+0 other overloads)
Security.Cryptography.X509Certificates.X509Certificate(handle: nativeint) : unit
   (+0 other overloads)
Security.Cryptography.X509Certificates.X509Certificate(cert: Security.Cryptography.X509Certificates.X509Certificate) : unit
   (+0 other overloads)
Security.Cryptography.X509Certificates.X509Certificate(rawData: byte [], password: string) : unit
   (+0 other overloads)
Security.Cryptography.X509Certificates.X509Certificate(rawData: byte [], password: Security.SecureString) : unit
   (+0 other overloads)
Security.Cryptography.X509Certificates.X509Certificate(fileName: string, password: string) : unit
   (+0 other overloads)
Security.Cryptography.X509Certificates.X509Certificate(fileName: string, password: Security.SecureString) : unit
   (+0 other overloads)
Security.Cryptography.X509Certificates.X509Certificate(info: Runtime.Serialization.SerializationInfo, context: Runtime.Serialization.StreamingContext) : unit
   (+0 other overloads)
type WebRequest =
  inherit MarshalByRefObject
  member Abort : unit -> unit
  member AuthenticationLevel : AuthenticationLevel with get, set
  member BeginGetRequestStream : callback:AsyncCallback * state:obj -> IAsyncResult
  member BeginGetResponse : callback:AsyncCallback * state:obj -> IAsyncResult
  member CachePolicy : RequestCachePolicy with get, set
  member ConnectionGroupName : string with get, set
  member ContentLength : int64 with get, set
  member ContentType : string with get, set
  member Credentials : ICredentials with get, set
  member EndGetRequestStream : asyncResult:IAsyncResult -> Stream
  ...

Full name: System.Net.WebRequest
val downloadFTPS : host:string -> username:string -> password:string -> fileName:string -> targetPath:string -> Async<'a>

Full name: Script.downloadFTPS
val host : string
val fileName : string
val targetPath : string
val async : AsyncBuilder

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.async
val client : FTPSClient
val fileToGet : Uri
Multiple items
type Uri =
  new : uriString:string -> Uri + 5 overloads
  member AbsolutePath : string
  member AbsoluteUri : string
  member Authority : string
  member DnsSafeHost : string
  member Equals : comparand:obj -> bool
  member Fragment : string
  member GetComponents : components:UriComponents * format:UriFormat -> string
  member GetHashCode : unit -> int
  member GetLeftPart : part:UriPartial -> string
  ...

Full name: System.Uri

--------------------
Uri(uriString: string) : unit
Uri(uriString: string, uriKind: UriKind) : unit
Uri(baseUri: Uri, relativeUri: string) : unit
Uri(baseUri: Uri, relativeUri: Uri) : unit
val target : string
type Path =
  static val DirectorySeparatorChar : char
  static val AltDirectorySeparatorChar : char
  static val VolumeSeparatorChar : char
  static val InvalidPathChars : char[]
  static val PathSeparator : char
  static member ChangeExtension : path:string * extension:string -> string
  static member Combine : [<ParamArray>] paths:string[] -> string + 3 overloads
  static member GetDirectoryName : path:string -> string
  static member GetExtension : path:string -> string
  static member GetFileName : path:string -> string
  ...

Full name: System.IO.Path
Path.Combine([<ParamArray>] paths: string []) : string
Path.Combine(path1: string, path2: string) : string
Path.Combine(path1: string, path2: string, path3: string) : string
Path.Combine(path1: string, path2: string, path3: string, path4: string) : string
Multiple items
type Async
static member AsBeginEnd : computation:('Arg -> Async<'T>) -> ('Arg * AsyncCallback * obj -> IAsyncResult) * (IAsyncResult -> 'T) * (IAsyncResult -> unit)
static member AwaitEvent : event:IEvent<'Del,'T> * ?cancelAction:(unit -> unit) -> Async<'T> (requires delegate and 'Del :> Delegate)
static member AwaitIAsyncResult : iar:IAsyncResult * ?millisecondsTimeout:int -> Async<bool>
static member AwaitTask : task:Task -> Async<unit>
static member AwaitTask : task:Task<'T> -> Async<'T>
static member AwaitWaitHandle : waitHandle:WaitHandle * ?millisecondsTimeout:int -> Async<bool>
static member CancelDefaultToken : unit -> unit
static member Catch : computation:Async<'T> -> Async<Choice<'T,exn>>
static member FromBeginEnd : beginAction:(AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg:'Arg1 * beginAction:('Arg1 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * beginAction:('Arg1 * 'Arg2 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromBeginEnd : arg1:'Arg1 * arg2:'Arg2 * arg3:'Arg3 * beginAction:('Arg1 * 'Arg2 * 'Arg3 * AsyncCallback * obj -> IAsyncResult) * endAction:(IAsyncResult -> 'T) * ?cancelAction:(unit -> unit) -> Async<'T>
static member FromContinuations : callback:(('T -> unit) * (exn -> unit) * (OperationCanceledException -> unit) -> unit) -> Async<'T>
static member Ignore : computation:Async<'T> -> Async<unit>
static member OnCancel : interruption:(unit -> unit) -> Async<IDisposable>
static member Parallel : computations:seq<Async<'T>> -> Async<'T []>
static member RunSynchronously : computation:Async<'T> * ?timeout:int * ?cancellationToken:CancellationToken -> 'T
static member Sleep : millisecondsDueTime:int -> Async<unit>
static member Start : computation:Async<unit> * ?cancellationToken:CancellationToken -> unit
static member StartAsTask : computation:Async<'T> * ?taskCreationOptions:TaskCreationOptions * ?cancellationToken:CancellationToken -> Task<'T>
static member StartChild : computation:Async<'T> * ?millisecondsTimeout:int -> Async<Async<'T>>
static member StartChildAsTask : computation:Async<'T> * ?taskCreationOptions:TaskCreationOptions -> Async<Task<'T>>
static member StartImmediate : computation:Async<unit> * ?cancellationToken:CancellationToken -> unit
static member StartWithContinuations : computation:Async<'T> * continuation:('T -> unit) * exceptionContinuation:(exn -> unit) * cancellationContinuation:(OperationCanceledException -> unit) * ?cancellationToken:CancellationToken -> unit
static member SwitchToContext : syncContext:SynchronizationContext -> Async<unit>
static member SwitchToNewThread : unit -> Async<unit>
static member SwitchToThreadPool : unit -> Async<unit>
static member TryCancelled : computation:Async<'T> * compensation:(OperationCanceledException -> unit) -> Async<'T>
static member CancellationToken : Async<CancellationToken>
static member DefaultCancellationToken : CancellationToken

Full name: Microsoft.FSharp.Control.Async

--------------------
type Async<'T>

Full name: Microsoft.FSharp.Control.Async<_>
static member Async.AwaitTask : task:Threading.Tasks.Task -> Async<unit>
static member Async.AwaitTask : task:Threading.Tasks.Task<'T> -> Async<'T>
val uploadFTPS : host:string -> username:string -> password:string -> filePath:string -> Async<Choice<'a,exn>>

Full name: Script.uploadFTPS
val filePath : string
Path.GetFileName(path: string) : string
val fileToSend : Uri
type WebRequestMethods =
  nested type File
  nested type Ftp
  nested type Http

Full name: System.Net.WebRequestMethods
type Ftp =
  static val DownloadFile : string
  static val ListDirectory : string
  static val UploadFile : string
  static val DeleteFile : string
  static val AppendFile : string
  static val GetFileSize : string
  static val UploadFileWithUniqueName : string
  static val MakeDirectory : string
  static val RemoveDirectory : string
  static val ListDirectoryDetails : string
  ...

Full name: System.Net.WebRequestMethods.Ftp
field WebRequestMethods.Ftp.UploadFile = "STOR"
static member Async.Catch : computation:Async<'T> -> Async<Choice<'T,exn>>
Raw view Test code New version

More information

Link:http://fssnip.net/7Ua
Posted:7 years ago
Author:Tuomas Hietanen
Tags: #ftp , #ftps