Search code examples
c#ftpftp-client

Automatically download files in FTP server


I don't have any knowledge about C# but I need to create an FTP server that automatically download a list of files (one by one, from the last to the first), so I downloaded some source codes of FTP servers and the most functional I found have a little problem, my task is to get a server that download files automatically, but the code I get open an window to select where to save the file.

How can i change it to download the files automatically?

(If possible, explain throughly how your code work, it will help me to better understand and learn C#)

private void ServerFileListView_DockChanged(object sender, EventArgs e)
{
    foreach (ListViewItem item in ServerFileListView.Items)
    {
      item.Selected = true;
    }

    byte[] file;

    Server.Download(MachineInfo.GetJustIP(), ServerFileListView.SelectedItems[0].SubItems[2].Text, out file);

    SaveFileDialog save = new SaveFileDialog();
    save.Title = "It saves the downloaded file.";
    save.SupportMultiDottedExtensions = false;
    save.Filter = "*.png|*.png";
    save.FileName = ServerFileListView.SelectedItems[0].SubItems[2].Text;
    if (save.ShowDialog() != System.Windows.Forms.DialogResult.Cancel)
    {
        System.IO.File.WriteAllBytes(save.FileName, file);
        MessageBox.Show(ServerFileListView.SelectedItems[0].SubItems[2].Text +" has been downloaded.", "FTP File Sharing", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    save.Dispose();
}

If you want more details ask in the comments.

(Sorry for bad speech, i'm not fluently in english)


Solution

  • You need to remove the SaveFileDialog() it is meant to save file interactively.

    • Get the list of the file and put in array
    • and loop (foreach) the array to run the download method
    • better yet, run the method in a separate thread or async, so it will not block the main thread.

    Pseudo:

    {run in thread
    
        if(ftp is connected)
        {
           connect;
           string listToDownload[] = getListFileFromServer;
            foreach (var item from listToDownload)
             {file = getFileFromServer;
              saveToDisk(file);
              }
        }
    }