如何使用C#从回收站恢复文件?

14

将文件移到回收站并清空回收站是比较常见的操作,但如何以编程方式从回收站中恢复文件呢?

3个回答

5

在纯C#中似乎没有解决方案。您最有可能需要使用P/Invoke来解决问题。本文提供了一种使用SHFileOperation API的C++解决方案。


2
我能看到唯一提到这个问题的是之前提到的链接codeproject,它提到了以下内容:
调用SHGetFolderLocation并传递CSIDL_BITBUCKET。 然后您可以像通常一样操作该文件夹。 您将不得不为SHGetFolderLocation函数创建一个交互操作。 CSIDL_BITBUCKET是虚拟回收站文件夹的CSIDL(“常量特殊项目ID列表”)值。 引用来自这里,需要与Windows shell进行交互。 MSDN还提到,这个函数已经被Vista中的另一个函数取代。

0
希望下面的代码能够恢复文件。请确保,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;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接