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);
}
}
If your
listBox1.Items
contains your filepath, you could simply pass it by de-referencing thefilepath
and delete it usingFile.Delete
like this:That is, if you add your paths to the
listBox1
usingFullName
instead of usingName
:If you don't want to not add the full name in the
listBox1
, you could also store theFolder
name separately, since it will not be changed anyway:And then you just use it like this:
If you have the proper permissions to access the file, this should work fine enough:
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:
See:
File.Delete()
at MSDNFile.Delete()
Make sure, you actually have something selected in your
ListBox
!