我正在制作个人使用的应用程序,它将组织.png文件,并允许我通过应用程序(通过ListView)从目录远程删除它们。
我有一个片段会从ListView中删除该文件,但不会从实际的文件目录中删除。我希望能够在单击删除时同时执行这两项操作。
private void deleteToolStripMenuItem1_Click(object sender, EventArgs e)
{
if (MessageBox.Show("This will delete the file from the folder. Are you sure?", "Warning", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) == DialogResult.Yes)
for (int i = fileDisplayListView.SelectedItems.Count - 1; i >= 0; i--)
{
ListViewItem item = fileDisplayListView.SelectedItems[i];
fileDisplayListView.Items[item.Index].Remove();
File.Delete(fbd.SelectedPath + fileDisplayListView.Items.ToString());
}
}
其他代码段以获取更多信息..
private void openToolStripButton_Click(object sender, EventArgs e)
{
fbd.ShowDialog();
DirectoryInfo di = new DirectoryInfo(fbd.SelectedPath);
directoryPath.Text = "Directory: " + fbd.SelectedPath;
FileInfo[] Files =
di.GetFiles("*.PNG*", SearchOption.AllDirectories);
if (Files.Length == 0)
MessageBox.Show("No .png files found in directory...", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Question);
fileDisplayListView.Items.Clear();
foreach (FileInfo f in Files)
{
ListViewItem item = new ListViewItem(f.Name);
this.fileDisplayListView.Items.Add(f.Name);
}
this.fileDisplayListView.View = View.Details;
this.fileDisplayListView.Refresh();
}
最后一部分File.Delete(fbd.SelectedPath + fileDisplayListView.Items.ToString());
不起作用。请帮忙!
答案 0 :(得分:1)
此代码获取目录中所有.jpg文件的列表,并将它们添加到ListView。按下按钮,它将删除所选的ListView元素和文件:
private FileInfo[] files;
public Form1()
{
InitializeComponent();
files = new DirectoryInfo(@"C:\Users\User\Pictures").GetFiles("*.jpg", SearchOption.AllDirectories);
foreach (var file in files)
{
listView1.Items.Add(file.Name);
}
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < listView1.SelectedItems.Count; i++)
{
var curentItem = listView1.SelectedItems[i];
foreach (FileInfo file in files)
{
if (curentItem.Text == file.Name)
{
listView1.Items.Remove(curentItem);
file.Delete();
i--;
}
}
}
}
答案 1 :(得分:0)
This is the snippet I used to fix the application. It is a lot more directly related to how I am approaching the problem.
if (MessageBox.Show("This will delete the file from the folder. Are you sure?", "Warning", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) == DialogResult.Yes)
for (int i = fileDisplayListView.SelectedItems.Count - 1; i >= 0; i--)
{
ListViewItem item = fileDisplayListView.SelectedItems[i];
string fpath = string.Empty;
fileDisplayListView.Items[item.Index].Remove();
fpath = fbd.SelectedPath.ToString() + "\\" + item.Text;
File.Delete(fpath);
}