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

3

14

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?

Starobin answered 26/5, 2009 at 15:47 Comment(0)
I
5

There seems not to be a solution in pure C#. You most likely have to resort to P/Invoke. This article presents a solution in C++ using the SHFileOperation API.

Ishmul answered 26/5, 2009 at 16:1 Comment(0)
E
2

The only other reference to this beyond the previously mentioned link to codeproject that I can see mentions this:

Call SHGetFolderLocation passing CSIDL_BITBUCKET.
Then you can manipulate that folder as usual.
You'll have to create an interop for the SHGetFolderLocation function.

CSIDL_BITBUCKET being the CSIDL ("constant special item ID list") value for the virtual Recycle Bin folder. The quote is taken from here, and will involve interop with the Windows shell. MSDN also mentions that this function has been deprecated in favour of another in Vista.

Elly answered 26/5, 2009 at 16:10 Comment(0)
D
0

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;
    }
Dotation answered 10/6, 2020 at 9:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.