Pregunta

Tengo esta clase que parece funcionar bastante bien en sistemas que no son de 64 bits.

using System;
using System.Runtime.InteropServices;

namespace DeleteToRecycleBin
{
/// <summary>
/// Send files directly to the recycle bin.
/// </summary>
public class RecybleBin
{

    /// <summary>
    /// Possible flags for the SHFileOperation method.
    /// </summary>
    [Flags]
    public enum FileOperationFlags: ushort 
    {
        /// <summary>
        /// Do not show a dialog during the process
        /// </summary>
        FOF_SILENT =                0x0004,
        /// <summary>
        /// Do not ask the user to confirm selection
        /// </summary>
        FOF_NOCONFIRMATION =        0x0010,
        /// <summary>
        /// Delete the file to the recycle bin.  (Required flag to send a file to the bin
        /// </summary>
        FOF_ALLOWUNDO =             0x0040,
        /// <summary>
        /// Do not show the names of the files or folders that are being recycled.
        /// </summary>
        FOF_SIMPLEPROGRESS =        0x0100,
        /// <summary>
        /// Surpress errors, if any occur during the process.
        /// </summary>
        FOF_NOERRORUI =             0x0400,
        /// <summary>
        /// Warn if files are too big to fit in the recycle bin and will need
        /// to be deleted completely.
        /// </summary>
        FOF_WANTNUKEWARNING =       0x4000,
    }

    /// <summary>
    /// File Operation Function Type for SHFileOperation
    /// </summary>
    public enum FileOperationType: uint
    {
        /// <summary>
        /// Move the objects
        /// </summary>
        FO_MOVE =                   0x0001,
        /// <summary>
        /// Copy the objects
        /// </summary>
        FO_COPY =                   0x0002,
        /// <summary>
        /// Delete (or recycle) the objects
        /// </summary>
        FO_DELETE =                 0x0003,
        /// <summary>
        /// Rename the object(s)
        /// </summary>
        FO_RENAME =                 0x0004,
    }



    /// <summary>
    /// SHFILEOPSTRUCT for SHFileOperation from COM
    /// </summary>
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
    private struct SHFILEOPSTRUCT
    {

        public IntPtr hwnd;
        [MarshalAs(UnmanagedType.U4)]
        public FileOperationType wFunc;
        public string pFrom;
        public string pTo;
        public FileOperationFlags fFlags;
        [MarshalAs(UnmanagedType.Bool)]
        public readonly bool fAnyOperationsAborted;
        public readonly IntPtr hNameMappings;
        public readonly string lpszProgressTitle;
    }

    [DllImport("shell32.dll", CharSet = CharSet.Auto)]
    private static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);

    /// <summary>
    /// Send file to recycle bin
    /// </summary>
    /// <param name="path">Location of directory or file to recycle</param>
    /// <param name="flags">FileOperationFlags to add in addition to FOF_ALLOWUNDO</param>
    public static bool Send(string path, FileOperationFlags flags)
    {
        try
        {
            SHFILEOPSTRUCT fs = new SHFILEOPSTRUCT
                                    {
                                        wFunc = FileOperationType.FO_DELETE,
                                        pFrom = path + '\0' + '\0',
                                        fFlags = FileOperationFlags.FOF_ALLOWUNDO | flags
                                    };

            // important to double-terminate the string.
            SHFileOperation(ref fs);
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

    /// <summary>
    /// Send file to recycle bin.  Display dialog, display warning if files are too big to fit (FOF_WANTNUKEWARNING)
    /// </summary>
    /// <param name="path">Location of directory or file to recycle</param>
    public static bool Send(string path) {
        return Send(path, FileOperationFlags.FOF_NOCONFIRMATION | FileOperationFlags.FOF_WANTNUKEWARNING);
    }

    /// <summary>
    /// Send file silently to recycle bin.  Surpress dialog, surpress errors, delete if too large.
    /// </summary>
    /// <param name="path">Location of directory or file to recycle</param>
    public static bool SendSilent(string path)
    {
        return Send(path, FileOperationFlags.FOF_NOCONFIRMATION | FileOperationFlags.FOF_NOERRORUI | FileOperationFlags.FOF_SILENT);

    }
}

}

¿Alguna forma de solucionarlo para que funcione bien también en x64?Intenté cambiar ushort a ulong y un par de modificaciones más, pero no funciona.

Sé que hay otras soluciones que requieren referencia a Microsoft.VisualBasic pero preferiría la forma p/invoke.

LA RESPUESTA CORRECTA ES:

En x64, SHFILEOPSTRUCT debe declararse sin el parámetro Pack = 1 o fallará.Esto es una verdadera molestia si desea que su código sea independiente de la plataforma, ya que debe declarar dos estructuras separadas, una con Pack = 1 y otra sin él.Luego debes declarar dos llamadas SHFileOperation diferentes, una para cada una de las estructuras.Luego tienes que decidir a cuál llamar dependiendo de si estás ejecutando 32 o 64 bits.

¿Fue útil?

Solución

¿Has mirado el PInvocar ¿sitio?Tiene una definición ligeramente diferente para el tipo FILEOPSTRUCT, lo que obliga a Unicode por un lado.Me pregunto si charset = auto confunde las cosas... como que su valor predeterminado es ANSI en 32 bits, pero Unicode en 64 bits y algo va mal en algún punto intermedio.

EDITAR;Además, el enfoque de referencia de Visual Basic es simple... Sé que la gente le tiene aversión por alguna razón, pero las DLL relevantes siguen siendo parte del marco central, por lo que no agregará ninguna dependencia nueva.

Otros consejos

Por extraño que parezca, .net ya tiene funciones para eliminar el contenedor de reciclaje ... pero están en el Microsoft.VisualBasic espacio de nombres. Específicamente, Microsoft.VisualBasic.FileIO.

using Microsoft.VisualBasic.FileIO;

// class declaration, method start here

// Send file to recycle bin without dialog
FileSystem.DeleteFile("pathToFile", UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);

// Send file to recycle bin without dialog
FileSystem.DeleteFile("pathToFile", UIOption.AllDialogs, RecycleOption.SendToRecycleBin);

// Directories are the same, but with DeleteDirectory instead
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top