I'm trying to make my own Mini File Manager in Windows Forms for learning purposes.
Can anyone please tell me how to implement the cancellation of the process of deleting folders, files from a PC with restoring deleted information in C#? (the progress bar is running and when you press the cancel button)
private void DeleteBtn_Click(object sender, EventArgs e)
{
DirectoryInfo[] checkeDirectoryInfos = NodesManager.GetCheckedNodes(SourceFilesTree);
if (MessageBox.Show("Are you sure you want permanently delete this items?", "Delete", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.OK)
{
FileManager.DeleteMethod(checkeDirectoryInfos);
foreach (TreeNode item in NodesManager.GetCheckedTreeNodes(SourceFilesTree))
{
item.Remove();
}
}
}
// this is from NodesManager class.
private static IEnumerable<TreeNode> CheckedNodes(TreeNodeCollection nodes)
{
foreach (TreeNode node in nodes)
{
// Yield this node.
if (node.Checked)
{
if (!node.Parent.Checked) //if the parent is checked we don't return the children (because they are selected by default)
{
yield return node;
}
}
// Yield the checked descendants of this node.
foreach (TreeNode checkedChild in CheckedNodes(node.Nodes))
yield return checkedChild;
}
}
// Return a list of the checked TreeView nodes.
private static IEnumerable<TreeNode> CheckedNodes(TreeView trv)
{
return CheckedNodes(trv.Nodes);
}
public static DirectoryInfo[] GetCheckedNodes(TreeView tree)
{
return CheckedNodes(tree)
.Select(node =>
{
DirectoryInfo file = new DirectoryInfo(GetParentString(node));
return file;
}).ToArray();
}
public static string GetParentString(TreeNode node)
{
if (node.Parent == null)
{
return node.Text;
}
return GetParentString(node.Parent) + node.Text + (node.Nodes.Count > 0 ? @"\" : string.Empty);
}
Delete method
public static void DeleteMethod(DirectoryInfo[] directories)
{
foreach (DirectoryInfo dir in directories)
{
if ((dir.Attributes & FileAttributes.Directory) != 0) //check if its a folder
{
try
{
dir.Delete(true);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
else // if it is a file
{
FileInfo file = new FileInfo(dir.FullName);
try
{
file.Delete();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
MessageBox.Show("Delete complete", "MiniFileManager",MessageBoxButtons.OK, MessageBoxIcon.Information);
}
This all is without a ProgressBar window form, but I want to know the idea how to implement this and how should this work(using TPL maybe with cancellation token?)