none
how to download ftp files from checkedlisbox in c# window forms RRS feed

  • Question

  • i am able to display file names from ftp server to checkedlist box

    now i want to download those files that are checked in checkedlistbox to a particular location

    private void button3_Click(object sender, EventArgs e)
            {
                

                FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://192.168.10.11");
                request.Credentials = new NetworkCredential("ftp-user", "123");
                request.Method = WebRequestMethods.Ftp.ListDirectory;

                StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream());

                string fileName = streamReader.ReadLine();

                while (fileName != null)
                {
                    

                    
                       
                    if(fileName!=null)
                    checkedListBox1.Items.Add(fileName).ToString();
                     fileName = streamReader.ReadLine();

                }

                request = null;
                streamReader = null;
            }
        }

    i dont know how to download the files that are checked in checkedlistbox

    Saturday, July 6, 2019 10:38 AM

All replies

  • Hello,

    To get the checked items

    foreach (var fileName in checkedListBox1.CheckedItems.Cast<string>())
    {
        // use fileName and download
    }

    For how to download

    https://docs.microsoft.com/en-us/dotnet/framework/network-programming/how-to-download-files-with-ftp


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Saturday, July 6, 2019 1:13 PM
    Moderator
  • i know how to get names of files from checkedboxes i don't know what to do with them so that they are downloaded in a particular directory or folder

    this is my actual question that you didn't answer but thanks for the help

    Sunday, July 7, 2019 7:35 AM
  • Hello,

    Did you look at the link I provided? You should be able to take the stream and write it to a file e.g.

    using (System.IO.FileStream output = new System.IO.FileStream(@"C:\MyOutput.pdf", FileMode.Create))
    {
      inputStream.CopyTo(output);
    }
    The file name in FileStream would come from the CheckedListBox.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Sunday, July 7, 2019 11:11 AM
    Moderator
  • thanks i got it myself after a lil bit of trying and experimenting

    WebClient client = new WebClient();
                    client.Credentials = new NetworkCredential("ftp-user", "123");
                    foreach (var fileName in checkedListBox1.CheckedItems.Cast<string>())
                    {
                        client.DownloadFile(
                          "ftp://192.168.10.10/"+fileName, @"C:\Users\zaybi\Documents\Visual Studio 2015\Projects\ftp2\ftp2\NewFolder1\"+fileName);
                    }

    Sunday, July 7, 2019 11:49 AM
  • now i have another question about uploading currently i am able to upload any file but just 1 single file at a time how can i upload multiple files at the same time?

    this is my code for uploading:-

    struct ftpSetting
            {
                public string Server { get; set; }
                public string Username { get; set; }

                public string Password { get; set; }

                public string FileName { get; set; }
                public string FullName { get; set; }
            }

            ftpSetting _inputParameter;
            private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
            {
               // MessageBox.Show("inside backgroundworker1_DoWork");
                
                    
                    string fileName = _inputParameter.FileName;
                    string fullName = _inputParameter.FullName;
                    string userName =_inputParameter.Username;
                    string passowrd = _inputParameter.Password;
                    string server = _inputParameter.Server;
                    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}", server, fileName)));
                    request.Method = WebRequestMethods.Ftp.UploadFile;
                    request.Credentials = new NetworkCredential(userName, passowrd);
                    Stream ftpStream = request.GetRequestStream();
                    FileStream fs = File.OpenRead(fullName);
                    byte[] buffer = new byte[1024];
                    double total = (double)fs.Length;
                    int byteRead = 0;
                    double read = 0;
                    do
                    {
                        if (!backgroundWorker1.CancellationPending)
                        {
                            byteRead = fs.Read(buffer, 0, 1024);
                            ftpStream.Write(buffer, 0, byteRead);
                            read += (double)byteRead;
                            double percentage = read / total * 100;
                            backgroundWorker1.ReportProgress((int)percentage);
                        }
                    }
                    while (byteRead != 0);
                    fs.Close();
                    ftpStream.Close();
                
              
            }

            private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
            {
               // MessageBox.Show("inside background worker_ProgressChanged");
                label4.Text = $"Uploaded {e.ProgressPercentage} %";
                progressBar1.Value = e.ProgressPercentage;
                progressBar1.Update();
            }

            private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
               // MessageBox.Show("inside background worker_RunWorkerCompleted");

                label4.Text = "upload completed";
            }

            private void button1_Click(object sender, EventArgs e)
            {
                //MessageBox.Show("inside button 1");

                try
                {
                    using (OpenFileDialog ofd = new OpenFileDialog() { Multiselect =false, ValidateNames = true, Filter = "All files|*.*" })
                    {
                        if (ofd.ShowDialog() == DialogResult.OK)
                        {
                            FileInfo fi = new FileInfo(ofd.FileName);
                            _inputParameter.Username = textBox2.Text;
                            _inputParameter.Password = textBox3.Text;
                            _inputParameter.Server = textBox1.Text;
                            _inputParameter.FileName = fi.Name;
                            _inputParameter.FullName = fi.FullName;
                            
                        }
                        // System.Windows.Forms.Application.DoEvents();

                       
                    }
                    backgroundWorker1.RunWorkerAsync();


                }
                catch (Exception ex)
                {
                    MessageBox.Show("error is:" + ex);
                }

            }

    Sunday, July 7, 2019 11:53 AM
  • Hi Jazz17,

    Thank you for posting here.

    Based on your description, you want to download the files that are checked in the checked listbox.

    You could try the following code.

     private void Form1_Load(object sender, EventArgs e)
            {
                string uri = "url";
                string username = "username";
                string password = "password";
                var list = FtplistFile(uri, username, password);
                foreach (var item in list)
                {
                    checkedListBox1.Items.Add(item);
                }
            }
            private void Button1_Click(object sender, EventArgs e)
            {
                var list = checkedListBox1.CheckedItems;
                string path = @"D:\Example";
                string uri = "url";
                string username = "username";
                string password = "password";
                foreach (var item in list)
                {
                    Ftpdownloadfile(Path.Combine(uri, item.ToString()), Path.Combine(path, item.ToString()), username, password);
                }
                MessageBox.Show("success");
    
            }
    
            private List<string> FtplistFile(string url, string username, string password) //get file name form ftp folder
            {
                FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(url);
                listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                listRequest.Credentials = new NetworkCredential(username, password);
                List<string> lines = new List<string>();
    
                using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
                using (Stream listStream = listResponse.GetResponseStream())
                using (StreamReader listReader = new StreamReader(listStream))
                {
                    while (!listReader.EndOfStream)
                    {
                        lines.Add(listReader.ReadLine());
                    }
                }
                List<string> name = new List<string>();
                foreach (var line in lines)
                {
                    string[] tokens =
                line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries);
                    string n = tokens[3];
                    name.Add(n);
                }
                return name;
            }
            private void Ftpdownloadfile(string to_uri, string path, string username, string password)
            {
    
                FtpWebRequest request =
    
                    (FtpWebRequest)WebRequest.Create(to_uri);
    
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(username, password);
    
                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (FileStream fs = new FileStream(path, FileMode.Create))
                        {
                            byte[] buffer = new byte[102400];
                            int read = 0;
                            do
                            {
                                read = responseStream.Read(buffer, 0, buffer.Length);
                                fs.Write(buffer, 0, read);
                                fs.Flush();
                            } while (!(read == 0));
    
                            fs.Flush();
                            fs.Close();
                        }
                    }
                }
    
    
            }

    For your another question, I suggest that you could create a new thread in c# forum.

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, July 8, 2019 2:45 AM
    Moderator
  • as i mentioned i alredy have done download file from checklis i,e download all the files that are checked 

    thanks for the effort and the concern but your code is very lengthy i think mine is better because its very simple and not complex like yours i know your code might be better but with respect i will prefer the code i posted as its very short.once again thanks for posting the code.

    Monday, July 8, 2019 3:21 AM
  • Hi Jazz17,

    Thanks for the feedback.

    I think the key to the problem is that if my code solves your problem. If solved, we can look for ways to simplify it. I think you could try the following code first instead of giving up it upon seeing long code. Not all problems have simple code.

    Thanks for understanding.

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, July 8, 2019 5:25 AM
    Moderator