如何检测驱动器在C#中是否有回收站?

时间:2011-10-10 20:05:07

标签: c# windows recycle-bin

我有一个使用FOF_ALLOWUNDO和SHFileOperation的应用程序,以便将文件移动到回收站。

某些可移动驱动器没有回收站。在这种情况下,SHFileOperation直接删除文件。我想向用户发出警告,要求直接删除文件。

为了做到这一点,我需要知道驱动器是否有回收站。

2 个答案:

答案 0 :(得分:7)

使用FOF_WANTNUKEWARNING。

  

如果文件在删除操作期间被永久销毁而不是回收,则发送警告。此标志部分覆盖FOF_NOCONFIRMATION。

答案 1 :(得分:1)

当我查看shell32.dll导出的函数时,我找到了一个名为SHQueryRecycleBin的函数。

如果 pszRootPath 中指定的驱动器具有回收站,则该函数返回0,否则返回-2147467259。

我将通过PInvoke使用此功能。

我使用P / Invoke Interop助手创建PInvoke代码。

以下是我的函数 DriveHasRecycleBin 的代码:

[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
    private struct SHQUERYRBINFO
    {
        /// DWORD->unsigned int
        public uint cbSize;

        /// __int64
        public long i64Size;

        /// __int64
        public long i64NumItems;
    }

    /// Return Type: HRESULT->LONG->int
    ///pszRootPath: LPCTSTR->LPCWSTR->WCHAR*
    ///pSHQueryRBInfo: LPSHQUERYRBINFO->_SHQUERYRBINFO*
    [System.Runtime.InteropServices.DllImportAttribute("shell32.dll", EntryPoint = "SHQueryRecycleBinW")]
    private static extern int SHQueryRecycleBinW([System.Runtime.InteropServices.InAttribute()] [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPTStr)] string pszRootPath, ref SHQUERYRBINFO pSHQueryRBInfo);

    public bool DriveHasRecycleBin(string Drive)
    {
        SHQUERYRBINFO Info = new SHQUERYRBINFO();
        Info.cbSize = 20; //sizeof(SHQUERYRBINFO)
        return SHQueryRecycleBinW(Drive, ref Info) == 0;
    }