Reputation: 51
I'm having a few problems deleting a file. Currently I have a listbox that stores the contents of a directory. I'm able to delete the entry from the listbox but not the corresponding file, so when the program is restarted the entry reappears as the file has not been deleted.
This is my code:
private void button3_Click(object sender, EventArgs e)
{
//removes selected item from listbox
foreach (int Index in listBox1.SelectedIndices.Cast<int>().Select(x => x).Reverse())
listBox1.Items.RemoveAt(Index);
string[] files = Directory.GetFiles(".\\Notes\\");
//Gets selected listbox item as string
string fileName = listBox1.GetItemText(listBox1.SelectedItem);
if (fileName.Equals(files))
{ // not deleting, yet!
File.Delete(".\\Notes\\"+ files);
}
MessageBox.Show("Note deleted!", "ModNote",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Upvotes: 0
Views: 72
Reputation: 4668
You have to change your if condition. Instead of
if (fileName.Equals(files))
{
File.Delete(".\\Notes\\"+files);
}
write
if (files.Contains(fileName))
{
File.Delete(".\\Notes\\"+fileName);
}
There are at least two issues: For once, you were comparing a string
(fileName
) with a string[]
(files
). Additionaly, you were constructing an incorrect path by concatenating ".\Notes\" with the array.
Upvotes: 1