Introduction

Use the System.NET.WebClient UploadFile method to copy files to an FTP server.

Running the Sample

The Debug tab in the Visual Studio project has command line arguments set up for running the application in the debugger.

Change the switch keys to connect to your FTP site as follows:

-source "<local folder path>"
-ftpdest "ftp://<host>/<directory path>"
-user <user name>
-pwd <password>

User and pwd are needed when a user name and password are required with the FTP connection. Remove these arguments if connecting by Anonymous FTP logon.

Example of running from the cmd window:

>WebClientFtp -source "C:\test" -ftpdest "ftp://ftp.acme.biz/test" -user ftpuser -pwd passwrd

Description

This sample demonstrates a simple way to create a command-line utility that copies files to your FTP server. The requirement here is that files on the workstation need to be FTP'd to a remote FTP server at scheduled intervals.

All files in the given source path are copied to the FTP server (excluding subfolders). An existing FTP directory path is supplied with the -ftpdest argument. Any existing files on the FTP server that are named the same as the source files will be replaced.

FTP\UploadFiles.cs holds the UploadFiles class. The UploadFiles constructor takes the args array and copies the arguments as Key-Value pairs<string, string> to ArgList. If requried arguments are missing, this is reported and the application exits. Otherwise, a member instance of WebClient (_webClient) is created.

Visual BasicC#
Edit|Remove
Public Sub New(ByVal args() As String) 
 
    Dim key As String = Nothing 
 
    For Each arg In args 
        If arg(0) = "-"Then 
            key = arg.ToLower 
        ElseIf key IsNot Nothing Then 
            If Not ArgList.ContainsKey(key) Then 
                ArgList.Add(key, arg) 
            End If 
        End If 
    Next 
 
    If (Not ArgList.ContainsKey("-source")) Or (Not ArgList.ContainsKey("-ftpdest")) Then 
        Console.WriteLine("Usage: WebClientFtp -source <path-to-local-folder> -ftpdest <uri-ftp-directory>") 
        Console.WriteLine("                  [ -user <userName> -pwd <password> ]") 
        Console.WriteLine("       -source and -ftpdest are required arguments") 
        Console.ReadKey(True) 
        Environment.Exit(1) 
    End If 
 
    _webClient = New WebClient() 
End Sub 
  

 

 Next (in Main), call the CopyFolderFiles method to copy files from -source to -ftpdest. CopyFolderFiles uses System.IO.Directory.GetFile to collect an array of files to be copied. Then ftpUpFile is called once for each file to upload these files to the ftpDest URI path. If ftpUpFile returns false, then the application waits for the time in milliseconds specified in the WaitInterval settings property.

Visual BasicC#
Edit|Remove
Public Sub CopyFolderFiles() 
    Dim sPath As String 
    sPath = ArgList("-source") 
 
    If Directory.Exists(sPath) Then 
        'get all files in path 
        Dim files() As String 
        files = Directory.GetFiles(sPath, "*.*", SearchOption.TopDirectoryOnly) 
        'if user and password exist, set credentials 
        If (ArgList.ContainsKey("-user")) And (ArgList.ContainsKey("-pwd")) Then 
            _webClient.Credentials = New NetworkCredential(ArgList("-user"), _ 
                                                           ArgList("-pwd")) 
        End If 
 
        Dim UploadCompleted As Boolean 
        Dim wait As Integer = My.Settings.WaitInterval 
        Dim ftpDest As String = ArgList("-ftpdest") 
 
        'loop through files in folder and upload 
        For Each file In files 
            Do 
                UploadCompleted = ftpUpFile(file, ftpDest) 
                If Not UploadCompleted Then 
                    Thread.Sleep(wait) 
                    wait += 1000 'wait an extra second after each failed attempt 
                End If 
            Loop Until UploadCompleted 
        Next 
    End If 
End Sub
  

Finally, ftpUpFile calls the UploadFile method to FTP the file to the server. The FTP STOR command is called by UploadFile in this case. The same method can also be used with an HTTP URI. HTTP POST is used to transfer to a site that has write permissions set.

 

Visual BasicC#
Edit|Remove
Private Function ftpUpFile(ByVal filePath As StringByVal ftpUri As String) _ 
                 As Boolean 
    Try 
        Console.WriteLine("Uploading file: " + filePath + " To: " + ftpUri) 
 
        'create full uri path 
        Dim file As String = ftpUri + "/" + Path.GetFileName(filePath) 
 
        'ftp the file to Uri path via the ftp STOR command 
        '(ignoring the the Byte[] array return since it is always empty in this case) 
        _webClient.UploadFile(file, filePath) 
        Console.WriteLine("Upload complete.") 
        Return True 
    Catch ex As Exception 
        'WebException is frequenty thrown for this condition:  
        '    "An error occurred while uploading the file" 
        Console.WriteLine(ex.Message) 
        Return False 
    End Try 
End Function 
 

So there you have it. A command-line utility best used in a scheduled task for copying (updating) files to a remote FTP server.

Source Code Files

C#

VB.NET

More Information

For more information on WebClient:
http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx

The interesting note about the UploadFile method is that on a production FTP site there will be failed file uploads. About 1 in 200 files fail in my experience. This will cause UploadFile to throw an exception. I find that if you pause some number of seconds, and then retry the upload, it works the next try.