Если ваш 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
}
Если вы не хотите не добавлять полное имя в listBox1
, вы также можете сохранить имя 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);
}
}
person
Ian
schedule
05.03.2016