How do I restore a file from the recycle bin using C#?

前端 未结 3 1663
无人共我
无人共我 2020-12-02 01:39

Moving files to the recycle bin and emptying the recycle bin are well documented, but how can a file be programmatically restored from the recycle bin?

3条回答
  •  暖寄归人
    2020-12-02 02:26

    Hope below code will work to restore the files. Please make sure, STA Calls only supported for shell calls

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

提交回复
热议问题