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

时间:2009-05-26 15:47:40

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

将文件移动到回收站并清空回收站已有详细记录,但如何从回收站以编程方式还原文件?

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

除了前面提到的codeproject链接之外,我能看到的唯一其他参考文献提到了这一点:

  

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

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

答案 2 :(得分:0)

希望以下代码可以恢复文件。请确保,仅Shell呼叫支持STA呼叫

     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;
    }