Search notes:

System.Net.WebClient - UploadFile()

The UploadFile() method of the System.Net.WebClient class can be used to upload a file to a remote server with a HTTP POST request or an FTP STOR command.

PowerShell example

Apparently, when using the Upload(address, fileName) overload of UploadFile, fileName needs to be passed as absolute (full) path, otherwise an Exception calling "UploadFile" with "2" arguments(s): "An exception occurred during a WebClient request." error is thrown.
Therefore, the name of the file to be uploaded is assigned to variable using get-item so that the full path can be passed with $localFile.fullName.
The following simple PowerShell example tries to demonstrate how a file can be uploaded to an FTP server:
$ftpHost    = 'ftp.somewhere.xy'
$username   = 'rene'
$password   = 'mySecretGarden'
$localFile  =  get-item theFile.txt
$remoteFile = "ftp://${ftpHost}/path/to/destination/theFile.txt"
$uri        =  new-object System.Uri($remoteFile)
$webclient  =  new-object System.Net.WebClient

$webClient.Credentials = new-object System.Net.NetworkCredential($username, $password);
$webclient.UploadFile($uri, $localFile.fullName)
Github repository .NET-API, path: /System/Net/WebClient/UploadFile.ps1

Upload multiple files

UploadFile() can be combined with a an iteration over files using get-childItem and the foreach statement to upload multiples files.
$webClient              = new-object System.Net.WebClient
$webClient.Credentials =  new-object System.Net.NetworkCredential($TQ84_RN_FTP_USER, $TQ84_RN_FTP_PW);

foreach ($file_ in get-childItem '*.png') {

   $file = split-path -leaf $file_

   $webClient.UploadFile(
      (new-object System.Uri("$TQ84_RN_FTP_DEST/$file")),  # format of TQ84_FTP_DEST: ftp://host.xyz/path/to/dir
      (get-item $file).FullName
   );

}
Github repository .NET-API, path: /System/Net/WebClient/UploadFiles.ps1
Because get-childItem returns System.IO.FileInfo objects, but I am interested in having a textual (string) representation of the files, I use split-path -leaf … to get such strings.

Connection pooling

Behind the scenes, as per this stackoverflow answer, a connection pool is established so that no new connection needs to be opened every time when a file is uploaded. Although the answer is about System.Net.WebRequest, its still relevant for WebClient because it uses WebRequest internally.

Index