How to delete from directory selected files in listbox

Ant6729

Well-known member
Joined
Jan 22, 2019
Messages
56
Programming Experience
Beginner
Hello, everyone!

I have a simple code

C#:
        private void button7_Click(object sender, EventArgs e) // ??????? ???????????? ?????????? ???????? ?????? ?? ????????
        {
            ListBox.SelectedObjectCollection selectedItems = new ListBox.SelectedObjectCollection(listBox1);
            selectedItems = listBox1.SelectedItems;


            if (listBox1.SelectedIndex != -1)
            {
                for (int i = selectedItems.Count - 1; i >= 0; i--)
                    listBox1.Items.Remove(selectedItems[i]);
            }
        }

And I need not only remove selected items from listbox, but to delete them from directory, they belong to also

Could you show me in code how its possible to do?
 
Firstly, what's the point of creating a new SelectedObjectCollection and then immediately discarding it and using an existing one? The 'new' keyword creates a new object so you don't use it unless you actually want a new object. If you're intending to use an existing object then you don't want a new object. Change this:
ListBox.SelectedObjectCollection selectedItems = new ListBox.SelectedObjectCollection(listBox1);
selectedItems = listBox1.SelectedItems;

to this:
ListBox.SelectedObjectCollection selectedItems = listBox1.SelectedItems;

There's no real need to specify the type of the variable either, as it will be inferred:
var selectedItems = listBox1.SelectedItems;


As for your question, you need to call File.Delete. You could have found that out easily enough simply by searching the web for "c# delete file". You need to pass the path of the file you want to delete as an argument. If you have the full path in the ListBox already then you can simply pass the item, which you will need to cast as type String. If I recall though, you are storing only the file name in the ListBox. In that case, you can use Path.Combine to recreate the file path from the folder path and file name. That means that you will have to keep the folder path somewhere when you populate the ListBox in the first place.
 
Help already provided. I told you to call File.Delete. Where have you made any attempt to do that? Did you read the documentation provided a link to? Did you search for examples on the web. From here, it doesn't look like you've done anything with the information already provided so I'll not be providing any more.
 
Ok
My code now

C#:
[COLOR=#000000][FONT=verdana]private void listBox1_SelectedIndexChanged(object sender, EventArgs e) // ????????[/FONT][/COLOR]

[COLOR=#000000][FONT=verdana]{[/FONT][/COLOR]

[COLOR=#000000][FONT=verdana]}[/FONT][/COLOR]


[COLOR=#000000][FONT=verdana]2) [/FONT][/COLOR]


[COLOR=#000000][FONT=verdana]private void button5_Click(object sender, EventArgs e) //Adding elements[/FONT][/COLOR]

{
            FolderBrowserDialog FBD = new FolderBrowserDialog();


            if (FBD.ShowDialog() == DialogResult.OK)
            {
                listBox1.Items.Clear();
                string[] files = Directory.GetFiles(FBD.SelectedPath);
                string[] dirs = Directory.GetDirectories(FBD.SelectedPath);


                foreach (string file in files)
                {
                    listBox1.Items.Add(Path.GetFileName(file));
                }


                listBox1.Sorted = true;


                foreach (string dir in dirs)
                {
                    listBox1.Items.Add(Path.GetFileName((dir)));
                }


            }


}



[COLOR=#000000][FONT=verdana]3)[/FONT][/COLOR]

[COLOR=#000000][FONT=verdana]private void button7_Click(object sender, EventArgs e) // deleting elements and files[/FONT][/COLOR]

        {
            ListBox.SelectedObjectCollection selectedItems = listBox1.SelectedItems;




            if (listBox1.SelectedIndex != -1)
            {
                for (int i = selectedItems.Count - 1; i >= 0; i--)
                    listBox1.Items.Remove(selectedItems[i]);
            }
        }
What can I do else?
 
Ok...

C#:
private void button5_Click(object sender, EventArgs e) 
        {
            List<FileInfo> files;
            using (var fbd = new FolderBrowserDialog())
            {
                if (fbd.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                files = Directory.GetFiles(fbd.SelectedPath).Select(f => new FileInfo(f)).ToList();
            }
            listBox1.DataSource = files;
            listBox1.DisplayMember = "Name";
            listBox1.ValueMember = "FullName";
        }
//--------------------------------------------------------------------------------------------------------------
        void DeleteFiles(ListBox listBox1)
        {
            {
                for (int i = listBox1.Items.Count - 1; i >= 0; i--)
                {
                    if (listBox1.GetSelected(i))
                    {
                        System.IO.File.Delete(listBox1.Items[i].ToString());
                    }
                }
            }
        }
 //--------------------------------------------------------------------------------------------------------------

        private void button7_Click(object sender, EventArgs e) 
        {
            DeleteFiles(listBox1);
        }

But now I cant remoove files from listbox...
 
Well
I m really confused with this challenge

May be because of aspect I cant see in my code
I dont know how to use it
 
This is your original loop:
for (int i = selectedItems.Count - 1; i >= 0; i--)
    listBox1.Items.Remove(selectedItems[i]);

In that code, 'selectedItems' is the name (maybe full path but I think name) of the file you want to delete. All you need to do is add a call to File.Delete to that loop and pass the full path of that file. Hopefully it is obvious that you need to either do it before the removal or assign the name/path to a variable before the removal. I've already told you how to create the full path from the name so you don't need anything further.
 
I try to do so

C#:
private void button5_Click(object sender, EventArgs e) //Adding elements


        {
            FolderBrowserDialog FBD = new FolderBrowserDialog();




            if (FBD.ShowDialog() == DialogResult.OK)
            {
                listBox1.Items.Clear();
                string[] files = Directory.GetFiles(FBD.SelectedPath);
                string[] dirs = Directory.GetDirectories(FBD.SelectedPath);


                foreach (string file in files)
                {
                    listBox1.Items.Add(Path.GetFileName(file));
                }


                listBox1.Sorted = true;
            }


            {
                List<FileInfo> files;


                using (var fbd = new FolderBrowserDialog())
                {
                    if (fbd.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }
                    files = Directory.GetFiles(fbd.SelectedPath).Select(f => new FileInfo(f)).ToList();
                }


                listBox1.DataSource = files;
                listBox1.DisplayMember = "Name";
                listBox1.ValueMember = "FullName";


            }
            
        }

and then


C#:
 private void button7_Click(object sender, EventArgs e) // ??????? ???????????? ?????????? ???????? ?????? ?? ????????
        {
            ListBox.SelectedObjectCollection selectedItems = new ListBox.SelectedObjectCollection(listBox1);
            selectedItems = listBox1.SelectedItems;




            if (listBox1.SelectedIndex != -1)
            {
                for (int i = selectedItems.Count - 1; i >= 0; i--)
                    listBox1.Items.Remove(selectedItems[i]);
                {
                    DeleteFiles(listBox1);
                }
            }


        }
        
        void DeleteFiles(ListBox listBox1)
        {
            {
                for (int i = listBox1.Items.Count - 1; i >= 0; i--)
                {
                    if (listBox1.GetSelected(i))
                    {
                        System.IO.File.Delete(listBox1.Items[i].ToString());
                    }
                }


            }
        }

But it doesnt work...



1.jpg

Could you show your variant of code how this issue could be solved?
 
Maybe you could try reading what's posted. I SPECIFICALLY pointed out the gotcha:
Hopefully it is obvious that you need to either do it before the removal or assign the name/path to a variable before the removal.
and you just ignored it. Is this:
for (int i = selectedItems.Count - 1; i >= 0; i--)
    listBox1.Items.Remove(selectedItems[i]);
{
    DeleteFiles(listBox1);
}

doing either of those things?

I also didn't notice that you were binding the ListBox, mainly because it wasn't mentioned anywhere but just included in code that I didn't read properly. If you have set the DataSource of the control then you can't add or remove items in the control directly. You have to do it via the data source.
 
Ok

C#:
[COLOR=#333333][FONT=Consolas]for (int i = selectedItems.Count - 1; i >= 0; i--)[/FONT][/COLOR]
[COLOR=#333333][FONT=Consolas]    listBox1.Items.Remove(selectedItems[i]);[/FONT][/COLOR]
[COLOR=#333333][FONT=Consolas]{[/FONT][/COLOR]
[COLOR=#333333][FONT=Consolas]    DeleteFiles(listBox1);[/FONT][/COLOR]
[COLOR=#333333][FONT=Consolas]}[/FONT][/COLOR]

I used it...in my first part (where remooving)


And how to make this code work...?

not "via the data source".


How to unite remooving and deleting?

Is this possible?

My previos part of code, where I try to add - suites only to a one of the next parts of code.

C#:
private void button7_Click(object sender, EventArgs e) // ??????? ???????????? ?????????? ???????? ?????? ?? ????????
        {
            ListBox.SelectedObjectCollection selectedItems = new ListBox.SelectedObjectCollection(listBox1);
            selectedItems = listBox1.SelectedItems;




            if (listBox1.SelectedIndex != -1)
            {
                for (int i = selectedItems.Count - 1; i >= 0; i--)
                    listBox1.Items.Remove(selectedItems[i]);
                {
                    DeleteFiles(listBox1);
                }
            }


        }
        


        void DeleteFiles(ListBox listBox1)
        {
            {
                for (int i = listBox1.Items.Count - 1; i >= 0; i--)
                {
                    if (listBox1.GetSelected(i))
                    {
                        System.IO.File.Delete(listBox1.Items[i].ToString());
                    }
                }
            }
        }


so, the question is open...
 
C#:
private void button5_Click(object sender, EventArgs e) 


        {
            string folderName;


            DirectoryInfo dinfo = new DirectoryInfo(@"");
            FileInfo[] Files = dinfo.GetFiles("*.txt");
            folderName = dinfo.FullName; 
            //MessageBox.Show(folderName);
            foreach (FileInfo file in Files)
            {
                listBox1.Items.Add(file.Name); 
            }
        }
        private void button7_Click(object sender, EventArgs e) 


        {
            if (listBox1.SelectedIndex != -1)
            {
                //Put your folder name here..
                DirectoryInfo dinfo = new DirectoryInfo(@"");
                string folderName = dinfo.FullName;
                string filepath = Path.Combine(folderName, listBox1.Items
[listBox1.SelectedIndex].ToString());
                if (File.Exists(filepath))
                    File.Delete(filepath);
                listBox1.Items.RemoveAt(listBox1.SelectedIndex);
            }
        }
[B]?[/B]

Thank me very match))
 
Back
Top Bottom