如果您
listBox1.Items
包含文件路径,您可以通过取消引用
filepath
并使用删除它
File.Delete
这样地:
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);
}
}
也就是说,如果您将路径添加到
listBox1
使用
FullName
而不是使用
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
}
如果您不想在
列表框1
,您还可以存储
Folder
名称单独命名,因为无论如何都不会更改:
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
}
然后你就这样使用它:
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);
}
}