【问题标题】:How do I restore a file from the recycle bin using C#?如何使用 C# 从回收站恢复文件?
【发布时间】:2024-05-18 04:45:02
【问题描述】:

将文件移动到回收站和清空回收站都有很好的记录,但是如何以编程方式从回收站中恢复文件呢?

【问题讨论】:

    标签: c# .net file-io recycle-bin


    【解决方案1】:

    在纯 C# 中似乎没有解决方案。您很可能不得不求助于 P/Invoke。 This article 提出了一个使用 SHFileOperation API 的 C++ 解决方案。

    【讨论】:

      【解决方案2】:

      除了前面提到的codeproject 链接之外,我能看到的唯一其他引用提到了这一点:

      通过 CSIDL_BITBUCKET 调用 SHGetFolderLocation。 然后,您可以照常操作该文件夹。 您必须为 SHGetFolderLocation 函数创建一个互操作。

      “CSIDL_BUCKET”是虚拟 RecycleBin 文件夹的常量。引用来自here,将涉及与 Windows shell 的互操作。 MSDN 还提到此功能已被弃用,取而代之的是 Vista 中的另一个功能。

      【讨论】:

        【解决方案3】:

        希望下面的代码可以恢复文件。请确保,STA 调用仅支持 shell 调用

             using System;
            using System.Collections;
            using System.Windows.Forms;
            using System.IO;
            using Shell32; //Reference Microsoft Shell Controls And Automation on the COM tab.
            using System.Runtime.InteropServices;
            using Microsoft.VisualBasic.FileIO;
            using System.Threading;
        
        
         private static void Restore(object param)
            {
                object[] args = (object[])param;
                string filename = (string)args[0];
                string filepath = (string)args[1];
        
        
                Shl = new Shell();
                Folder Recycler = Shl.NameSpace(10);
                var c = Recycler.Items().Count;
        
                var _recycler = Recycler.Items();
                for (int i = 0; i < _recycler.Count; i++)
                {
                    FolderItem FI = _recycler.Item(i);
                    string FileName = Recycler.GetDetailsOf(FI, 0);
                    if (Path.GetExtension(FileName) == "") FileName += Path.GetExtension(FI.Path);
                    //Necessary for systems with hidden file extensions.
        
                    string FilePath = Recycler.GetDetailsOf(FI, 1);
                    if (filepath == Path.Combine(FilePath, FileName))
                    {
                        DoVerb(FI, "ESTORE");
                        break;                 
                    }
                }        
            }
        
            private static bool DoVerb(FolderItem Item, string Verb)
            {
                foreach (FolderItemVerb FIVerb in Item.Verbs())
                {
                    if (FIVerb.Name.ToUpper().Contains(Verb.ToUpper()))
                    {
                        FIVerb.DoIt();
                        return true;
                    }
                }
                return false;
            }
        

        【讨论】:

          最近更新 更多