1

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);
        }
    }
Luke_i
  • 163
  • 1
  • 2
  • 13
  • 1
    Do you have the file path in your listbox Items? is it fullpath? – Ian Mar 05 '16 at 10:45
  • Possible duplicate of [How to delete a file after checking whether it exists](http://stackoverflow.com/questions/6391711/how-to-delete-a-file-after-checking-whether-it-exists) – Eugene Podskal Mar 05 '16 at 10:45

2 Answers2

3

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);
    }
}
Ian
  • 30,182
  • 19
  • 69
  • 107
  • like that its still removing them only from my listbox – Luke_i Mar 05 '16 at 10:54
  • @Luke_i can you show how the text in your `listBox1` looks like? the keyword here is *fullpath*. If it is wrong path, then it is due to the path not there then you cannot remove the file at all... – Ian Mar 05 '16 at 10:56
  • it lists them as ' Test.xml', 'Test2.xml' all underneath each other – Luke_i Mar 05 '16 at 10:58
  • But if it is loading them then I cannot have the wrong file path... I guess – Luke_i Mar 05 '16 at 10:59
  • 1
    @Luke_i that's it! there is no folder path there! Do you see that? ;) This is because when you first at the file, you only add the `file.Name`. If you add it like this: `listBox1.Items.Add(file.FullName);` then you have the fullpath – Ian Mar 05 '16 at 11:00
  • I get it now... XD Silly me.. foreach (FileInfo file in Files) { listBox1.Items.Add(file.Name); } ... so how do I add it correctly? Thanks – Luke_i Mar 05 '16 at 11:01
  • @Luke_i use `FullName` instead of `Name` – Ian Mar 05 '16 at 11:04
  • Thanks it worked! But I would like it to show me the name of the file instead the path if possible. Thanks – Luke_i Mar 05 '16 at 11:06
  • @Ian what's new with the edit? I can't see the point of the variable `folderName`. – Fᴀʀʜᴀɴ Aɴᴀᴍ Mar 05 '16 at 11:10
  • @FᴀʀʜᴀɴAɴᴀᴍ It is only for display purpose. That means, he only needs to store the folder name once. And then he uses it as part of the filepath by `Path.Combine` such that the `listBox1` will actually only show the `fileName` – Ian Mar 05 '16 at 11:11
  • @Ian shouldn't it be `data\\Teachers\\\` then? – Fᴀʀʜᴀɴ Aɴᴀᴍ Mar 05 '16 at 11:12
  • @Ian cant it be simplier? Instead of showing the full path I show the Name? I cant use a specific Destination to save my files in – Luke_i Mar 05 '16 at 11:12
  • @FᴀʀʜᴀɴAɴᴀᴍ oh you are right! I didn't see that! it should be the data\\Teachers – Ian Mar 05 '16 at 11:13
  • @Luke_i Another way would be to create a separate class which can contain both the file name and the full file name. Then you could override its `ToString()` function to return just the name. But when you access it you can still get the path by accessing the property. – Fᴀʀʜᴀɴ Aɴᴀᴍ Mar 05 '16 at 11:16
  • @Luke_i, yes it can be simplified, because you have directory info that refers to data\\Teachers\\ already. Credit goes to Farhan Anam to notice it. I updated my answer to make it simpler and more flexible - referring relatively to your directory info in the initialization – Ian Mar 05 '16 at 11:20
  • @Ian Ok that might be with the fullpath but if the file is not found, shouldn't it throw some other exception and not a `NullReferenceException'? – Fᴀʀʜᴀɴ Aɴᴀᴍ Mar 05 '16 at 11:21
  • @Ian In fact, it shouldn't even throw an exception! – Fᴀʀʜᴀɴ Aɴᴀᴍ Mar 05 '16 at 11:22
  • @FᴀʀʜᴀɴAɴᴀᴍ hmm... if it throws exception, means it is not there... that means there isn't item. – Ian Mar 05 '16 at 11:23
  • @Ian Oh sorry, the OP didn't mention an Exception when using your answer. Sorry again ;) It was my answer that caused the exception, probably because of using `SelectedItem`.. – Fᴀʀʜᴀɴ Aɴᴀᴍ Mar 05 '16 at 11:23
  • @FᴀʀʜᴀɴAɴᴀᴍ ah, I got it. In your case, you remove the item from the `listBox` first, and then in the next line, you do `SelectedItem.ToString()` which have been removed by the previous line. That is why you got an `Exception` - `NullException`. :) fix it out! – Ian Mar 05 '16 at 11:25
  • @Luke_i do you notice: `Path.Combine(folderName, ` there is `folderName` slipped there... ;) it is used to create the `fullpath` – Ian Mar 05 '16 at 11:37
  • @Luke_i ah yes, I didn't mean to create new code lines there... it is just to bring you to attention that there is `folderName` slipped there... – Ian Mar 05 '16 at 11:39
  • @Ian i cannot use the folderName because I never used it anywhere in the Delete btn Action. I used it in the Form Load action. thanks – Luke_i Mar 05 '16 at 11:41
  • @Ian nvm It worked.. i just took out the string folderName because i used it into the the formLoad action. Thanks a lot :D – Luke_i Mar 05 '16 at 11:44
1

If you have the proper permissions to access the file, this should work fine enough:

System.IO.File.Delete(listBox1.SelectedItem.ToString());

The above code is applicable only if the ListBoxItem is a string. Otherwise you can consider casting it to your Data class and using the appropriate property. Seeing the code you posted, it is not required.

So your final code will be like this:

private void tDeletebtn_Click(object sender, EventArgs e)

{
    if (listBox1.SelectedIndex != -1)
    {
        System.IO.File.Delete(listBox1.Items[listBox1.SelectedIndex].ToString());
        listBox1.Items.RemoveAt(listBox1.SelectedIndex);
    }
}

See:

Make sure, you actually have something selected in your ListBox!

Fᴀʀʜᴀɴ Aɴᴀᴍ
  • 6,131
  • 5
  • 31
  • 52
  • Like that it gave me a Null Reference Exception was unhandled - Object reference not set to an instance of an object. – Luke_i Mar 05 '16 at 10:49
  • OK, the credit for the folder path goes to you.. ;) voted up. – Ian Mar 05 '16 at 11:17
  • 1
    No, no, I mean, the importance is the sequence, not whether it is using `SelectedItem` or `SelectedIndex` – Ian Mar 05 '16 at 11:26