[英]How to implement the cancellation of the process of deleting folders, files from a PC with restoring deleted information in C#?
我正在尝试出于学习目的在Windows窗体中制作我自己的迷你文件管理器。
谁能告诉我如何用PC恢复带有C#的已删除信息来取消删除文件夹,文件的过程吗? (进度条正在运行,并且在您按“取消”按钮时)
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);
}
删除方式
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);
}
所有这些都没有ProgressBar窗口表单,但是我想知道如何实现此想法以及如何工作(使用TPL或取消标记吗?)
考虑到取消,通常在C#中使用带有取消标记的代码来完成 。
考虑到还原,纯C#中没有内置解决方案。 如果要还原它们,则必须将其移动到充当回收站的自定义文件夹中,而不是删除它们。 您可能要使用Shell Win32 API,可以在其中删除文件到回收站并还原它们。 但是您需要使用P / Invoke来访问Win32 API,它变得相当复杂,这似乎并不是您想要的。 另外,您可能要考虑UWP,因为C#支持在那里删除到“回收站”,但是目前无法恢复它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.