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

问题描述 投票:12回答:3

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

c# .net file-io recycle-bin
3个回答
4
投票

在纯C#中似乎没有一个解决方案。你很可能不得不求助于PInvoke。这篇文章 在C++中提出了一个解决方案,使用 SHFileOperation API。


1
投票

除了前面提到的链接之外,唯一的其他参考文献是关于 代码工程 我所看到的提到了这一点。

调用SHGetFolderLocation 传递CSIDL_BITBUCKET. 然后你就可以像平常一样操作那个文件夹了。 你必须为SHGetFolderLocation函数创建一个interop。

"CSIDL_BUCKET "是虚拟RecycleBin文件夹的常量。引文来自 此处并将涉及与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;
    }
© www.soinside.com 2019 - 2024. All rights reserved.