How to implement the function of downloading all files from the X directory to the Y directory on ftp.

I have achieved that one file is being sent. But there are two problems:

1 In a directory a lot of files under the directory.

2 If the file already exists with the same name, it is necessary to overwrite the new file.

requestFTPUploader = (FtpWebRequest)WebRequest.Create("ftp://127.0.0.1/Destination/" + fileName); requestFTPUploader.Credentials = new NetworkCredential("user", "pass"); requestFTPUploader.Method = WebRequestMethods.Ftp.UploadFile; FileInfo fileInfo = new FileInfo(filepath); FileStream fileStream = fileInfo.OpenRead(); int bufferLength = 2048; byte[] buffer = new byte[bufferLength]; try { Stream uploadStream = requestFTPUploader.GetRequestStream(); int contentLength = fileStream.Read(buffer, 0, bufferLength); while (contentLength != 0) { uploadStream.Write(buffer, 0, contentLength); contentLength = fileStream.Read(buffer, 0, bufferLength); } uploadStream.Close(); fileStream.Close(); } catch (Exception exception) { Console.WriteLine(exception.Message.ToString()); } Console.WriteLine(fileName + "Uploaded"); 

Those. need a function with input parameters: user, pass, sourceDir, destinationDir. And the output is copied / replaced files to the server using the ftp protocol.

    1 answer 1

    1. A lot of files? Well, it means that it will be copied for a long time. This is not a problem, is it?
    2. Use WebRequestMethods.Ftp.DeleteFile :

       var requestFtpDeleter = (FtpWebRequest)WebRequest.Create( "ftp://127.0.0.1/Destination/" + fileName); requestFtpDeleter.Credentials = new NetworkCredential("user", "pass"); requestFtpDeleter.Method = WebRequestMethods.Ftp.DeleteFile; using (var response = (FtpWebResponse)requestFtpDeleter.GetResponse()) { bool isSuccessful = response.StatusCode >= 200 && response.StatusCode < 300; // ΠΈΡΠΊΠ»ΡŽΡ‡Π΅Π½ΠΈΠ΅ ΠΏΡ€ΠΈ ошибкС? } 
    • In other words, do you suggest deleting all files first, and then uploading new ones? This is of course a way out, but I don't like him. In addition, this is not a working version since there are some files that are not related to the project, but they are here and will be deleted. Plus sign set. :) - Anonymous
    • @Anonymous: No, of course, not all. Only those files that you want to write, and you answered that such a file already exists. Then the existing file must be deleted, and if successful, try to write again. - VladD
    • And for example, does a WinSCP client also work? Does each file separately consider? - Anonymous
    • @Anonymous: And you look in the FTP protocol, is there a batch file transfer in it? I did not find. - VladD
    • Ultimately, implemented as written by @VladD, first we compare if there is a file, then we delete it, then we write this file again. - Anonymous