March 10th, 2014

Programmatically uploading a file to an FTP site

Today’s Little Program uploads a file to an FTP site in binary mode with the assistance of the Wininet library. This program has sat in my bag of tools for years.

#define STRICT
#define UNICODE
#include <windows.h>
#include <wininet.h>
#include <shellapi.h>
int __cdecl wmain(int argc, PWSTR argv[])
{
 if (argc == 6) {
  HINTERNET hintRoot = InternetOpen(TEXT("ftpput/1.0"),
            INTERNET_OPEN_TYPE_DIRECT,
            NULL, NULL, 0);
  if (hintRoot) {
   HINTERNET hintFtp = InternetConnect(hintRoot,
            argv[1],
            INTERNET_DEFAULT_FTP_PORT,
            argv[2],
            argv[3],
            INTERNET_SERVICE_FTP,
            INTERNET_FLAG_PASSIVE,
            NULL);
   if (hintFtp) {
    FtpPutFile(hintFtp, argv[4], argv[5],
         FTP_TRANSFER_TYPE_BINARY,
         NULL);
    InternetCloseHandle(hintFtp);
   }
   InternetCloseHandle(hintRoot);
  }
 }
 return 0;
}

The program accepts five command line arguments:

  1. site (no “ftp://” in front)
  2. userid
  3. password
  4. path for the file to upload
  5. location to place the uploaded file

For example, I might say ftpput ftp.contoso.com admin seinfeld newversion.zip subdir/newversion.zip

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.