How do I detect if a drive has a recycle bin in C#?
I have an开发者_JAVA技巧 application which uses the FOF_ALLOWUNDO with SHFileOperation in order to move files to the recycle bin.
Some removable drives do not have a recycle bin. In this case SHFileOperation deletes the files directly. I want to give a warning to the user that the files are going to be deleted directly.
In order to do this I need to know if the drive has a recycle bin.
Use FOF_WANTNUKEWARNING.
Send a warning if a file is being permanently destroyed during a delete operation rather than recycled. This flag partially overrides FOF_NOCONFIRMATION.
I found a function called SHQueryRecycleBin when I looked at the functions exported by shell32.dll.
If the drive specified in pszRootPath has a recycle bin the function returns 0 otherwise it returns -2147467259.
I'm going to use this function via PInvoke.
I used the P/Invoke Interop Assistant to create the PInvoke code.
Here is the code of my function 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;
}
精彩评论