2010-02-26 3 views
3

비 64 비트에서 잘 작동하는 것으로 보이는이 클래스가 있습니다.C#의 Windows x64에서 휴지통으로 파일 삭제

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

    } 
} 

}

너무 64에 잘 작동되도록 문제를 해결할 수있는 방법? 나는 ulong과 몇 가지 다른 수정에 chaning 시도를 시도했지만 작동하지 않습니다.

Microsoft.VisualBasic에 대한 참조가 필요한 다른 솔루션이 있지만 p/invoke 방식을 선호합니다.

정답은 : 64에서

는 SHFILEOPSTRUCT는 팩 = 1 개 매개 변수없이 선언해야하거나 실패합니다. Pack = 1 인 코드와 두 코드가없는 코드를 별도로 선언해야하기 때문에 코드를 플랫폼에 독립적으로 사용하려면 코드가 실제로 필요합니다. 그런 다음 각 구조에 대해 하나씩 두 개의 다른 SHFileOperation 호출을 선언해야합니다. 그런 다음 32 또는 64 비트에서 실행 중인지 여부에 따라 어느 것을 호출할지 결정해야합니다.

답변

2

PInvoke 사이트를 보았습니까? 그것은 FILEOPSTRUCT 유형에 대해 약간 다른 정의를 가지므로 한 가지 이유로 유니 코드를 강요합니다. 만약 charset = auto가 혼란 스럽다면 ... 32 비트에서는 ANSI가 기본값이지만, 64 비트에서는 Unicode가 중간에 잘못되어 있습니다.

EDIT; 또한 Visual Basic 참조 방법은 간단합니다 ... 사람들이 어떤 이유로 혐오감을 갖지만 관련 DLL은 여전히 ​​핵심 프레임 워크의 일부이므로 새로운 종속성을 추가하지는 않습니다.

+0

[StructLayout (LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)] 내에 문제가 발생합니다. 64 비트의 경우 Pack = 1을 제거해야합니다. 당신이 나를 PInvoke 사이트로 지적했기 때문에 심지어 그것을 말합니다. (기사의 맨 아래에 64 비트 OS 일 때 Pack = 1을 제거하라는 메시지가 나타납니다.) – MadBoy

+0

하하, 나는 그저 아래까지 스크롤하지 않았습니다. –

+0

필자는 FILEOPSTRUCT에 대해 Pack = 1로 64 비트 Windows 7을 사용하고 있으며 아무런 문제없이 저와 함께 작동합니다 : | – TheBlueSky

6

이상하게도 .NET에는 이미 휴지통으로 삭제하는 기능이 있지만 ... Microsoft.VisualBasic 네임 스페이스에 있습니다. 구체적으로는 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 
+0

어색하게 참 ... – RvdK

+0

나는이 솔루션을 알고 있지만 VisualBasic에 대한 참조를 사용하지 않고이 솔루션을 선호합니다. – MadBoy

+0

@MadBoy 왜 Microsoft.VisualBasic을 참조하지 않으려합니까? – Nick