Search code examples
c#xmllistboxdelete-fileselectedindex

Delete Selected File from Listbox and Folder


I want to Delete the Selected File from Listbox and Folder. For now it's only removing it from the Listbox. Now I want it to be removed also from the Folder. Thanks

    private void tDeletebtn_Click(object sender, EventArgs e)

    {
        if (listBox1.SelectedIndex != -1)
            listBox1.Items.RemoveAt(listBox1.SelectedIndex);
    }

   private void TeacherForm_Load(object sender, EventArgs e)
    {
        DirectoryInfo dinfo = new DirectoryInfo(@"data\\Teachers\\");
        FileInfo[] Files = dinfo.GetFiles("*.xml");
        foreach (FileInfo file in Files)
        {
            listBox1.Items.Add(file.Name);
        }
    }

Solution

  • If your listBox1.Items contains your filepath, you could simply pass it by de-referencing the filepath and delete it using File.Delete like this:

    private void tDeletebtn_Click(object sender, EventArgs e)
    {
        if (listBox1.SelectedIndex != -1){
            string filepath = listBox1.Items[listBox1.SelectedIndex].ToString();
            if(File.Exists(filepath))
                File.Delete(filepath);            
            listBox1.Items.RemoveAt(listBox1.SelectedIndex);
        }
    }
    

    That is, if you add your paths to the listBox1 using FullName instead of using Name:

        DirectoryInfo dinfo = new DirectoryInfo(@"data\\Teachers\\");
        FileInfo[] Files = dinfo.GetFiles("*.xml");
        foreach (FileInfo file in Files)
        {
            listBox1.Items.Add(file.FullName); //note FullName, not Name
        }
    

    If you don't want to not add the full name in the listBox1, you could also store the Folder name separately, since it will not be changed anyway:

    string folderName; //empty initialization
    .
    .
        DirectoryInfo dinfo = new DirectoryInfo(@"data\\Teachers\\");
        FileInfo[] Files = dinfo.GetFiles("*.xml");
        folderName = dinfo.FullName; //here you initialize your folder name
        //Thanks to FᴀʀʜᴀɴAɴᴀᴍ
        foreach (FileInfo file in Files)
        {
            listBox1.Items.Add(file.Name); //just add your filename here
        }
    

    And then you just use it like this:

    private void tDeletebtn_Click(object sender, EventArgs e)
    {
        if (listBox1.SelectedIndex != -1){
            //Put your folder name here..
            string filepath = Path.Combine(folderName, listBox1.Items[listBox1.SelectedIndex].ToString());
            if(File.Exists(filepath))
                File.Delete(filepath);            
            listBox1.Items.RemoveAt(listBox1.SelectedIndex);
        }
    }