简体   繁体   中英

Copy and delete the file from the FTP SERVER using Windows Service in c#

I am trying to implement a windows service that will ping a FTP site and copy its contents once in every 3 hours.

This service has functions to

  1. List all files in the FTP site

  2. Copy one file

  3. Delete the copied file

  4. Repeats step 2 and 3 for all files in the site

Use FtpWebRequest . MSDN has samples for everything you need:

List all files

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/");
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

Copy one file

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.DownloadFile;

Delete the copied file

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.DeleteFile;

There are two classes which will be of great value to you for FTP. First, FtpWebRequest and second, FtpWebResponse . As for writing a windows service: this , and this should be helpful as well.

An example lifted from MSDN to delete a file:

public static bool DeleteFileOnServer(Uri serverUri)
{
    // 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;
    }
    // Get the object used to communicate with the server.
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
    request.Method = WebRequestMethods.Ftp.DeleteFile;

    FtpWebResponse response = (FtpWebResponse) request.GetResponse();
    Console.WriteLine("Delete status: {0}",response.StatusDescription);  
    response.Close();
    return true;
}

With a little bit of work you should be able to modify that to do every thing you need in terms of FTP Access.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM