HOW TO:将文件删除到回收站(VB.NET,C#分别实现)

需要通过P/Invoke调用Shell API来实现。

VB.NET的代码:
Module Module1
Sub Main()
Console.WriteLine(DeleteToRecycleBin("C:\A"))
End Sub

Function DeleteToRecycleBin(ByVal path As String) As Integer
Dim pm As New SHFILEOPSTRUCT
With pm
.wFunc = Convert.ToUInt32(FO_DELETE)
.pFrom = path & Chr(0)
.pTo = Nothing
.fFlags = Convert.ToUInt16(FOF_ALLOWUNDO Or FOF_NOCONFIRMATION)
End With
Return SHFileOperation(pm)
End Function

Public Const FO_DELETE As Integer = &H3
Public Const FOF_NOCONFIRMATION As Short = &H10
Public Const FOF_ALLOWUNDO As Short = &H40

Declare Unicode Function SHFileOperation Lib "shell32.dll" (<In, Out()> ByVal sfo As SHFILEOPSTRUCT) As Int32

 1<structlayout(layoutkind.sequential, charset:="CharSet.Ansi)"> _   
 2Public Class SHFILEOPSTRUCT   
 3Public hwnd As IntPtr   
 4Public wFunc As UInt32   
 5Public pFrom As String   
 6Public pTo As String   
 7Public fFlags As UInt16   
 8Public fAnyOperationsAborted As Int32   
 9Public hNameMappings As IntPtr   
10Public lpszProgressTitle As String   
11End Class   
12End Module   
13  
14调用:DeleteToRecycleBin("C:\A")   
15  
16C#代码:   
17private const int FO_DELETE = 0x3;   
18private const ushort FOF_NOCONFIRMATION = 0x10;   
19private const ushort FOF_ALLOWUNDO = 0x40;   
20  
21[DllImport("shell32.dll", SetLastError=true, CharSet=CharSet.Unicode)]   
22private static extern int SHFileOperation([In,Out] _SHFILEOPSTRUCT str);   
23  
24[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]   
25public class _SHFILEOPSTRUCT   
26{   
27public IntPtr hwnd;   
28public UInt32 wFunc;   
29public string pFrom;   
30public string pTo;   
31public UInt16 fFlags;   
32public Int32 fAnyOperationsAborted;   
33public IntPtr hNameMappings;   
34public string lpszProgressTitle;   
35}   
36  
37public static int Delete(string path)   
38{   
39_SHFILEOPSTRUCT pm = new _SHFILEOPSTRUCT();   
40pm.wFunc = FO_DELETE;   
41pm.pFrom = path + '\0';   
42pm.pTo = null;   
43pm.fFlags = FOF_ALLOWUNDO ¦ FOF_NOCONFIRMATION;   
44return SHFileOperation(pm);   
45}   
46调用:Class1.Delete("C:\\\temp.txt");   
47  
48注:返回值为0表示调用成功,非0表示调用失败。   
49需要引用System.Runtime.InteropServices命名空间。   
50  
51主题词:回收站,删除文件,P/Invoke,SHFileOperation</structlayout(layoutkind.sequential,>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus