C# 如何将文件放入回收站而不是删除?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you place a file in recycle bin instead of delete?
提问by Brian Leahy
Programmatic solution of course...
程序化解决方案当然...
采纳答案by TK.
http://www.daveamenta.com/2008-05/c-delete-a-file-to-the-recycle-bin/
http://www.daveamenta.com/2008-05/c-delete-a-file-to-the-recycle-bin/
From above:
从上面:
using Microsoft.VisualBasic;
string path = @"c:\myfile.txt";
FileIO.FileSystem.DeleteDirectory(path,
FileIO.UIOption.OnlyErrorDialogs,
RecycleOption.SendToRecycleBin);
回答by Ishmaeel
You need to delve into unmanaged code. Here's a static class that I've been using:
您需要深入研究非托管代码。这是我一直在使用的静态类:
public static class Recycle
{
private const int FO_DELETE = 3;
private const int FOF_ALLOWUNDO = 0x40;
private const int FOF_NOCONFIRMATION = 0x0010;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
public struct SHFILEOPSTRUCT
{
public IntPtr hwnd;
[MarshalAs(UnmanagedType.U4)]
public int wFunc;
public string pFrom;
public string pTo;
public short fFlags;
[MarshalAs(UnmanagedType.Bool)]
public bool fAnyOperationsAborted;
public IntPtr hNameMappings;
public string lpszProgressTitle;
}
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);
public static void DeleteFileOperation(string filePath)
{
SHFILEOPSTRUCT fileop = new SHFILEOPSTRUCT();
fileop.wFunc = FO_DELETE;
fileop.pFrom = filePath + 'Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(file.FullName,
Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,
Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin);
' + '##代码##';
fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;
SHFileOperation(ref fileop);
}
}
Addendum:
附录:
- Tsk tsk @ Jeff for "using Microsoft.VisualBasic" in C# code.
- Tsk tsk @ MS for putting all the goodies in VisualBasic namespace.
- Tsk tsk @ Jeff 在 C# 代码中“使用 Microsoft.VisualBasic”。
- Tsk tsk @ MS 将所有好东西都放在 VisualBasic 命名空间中。
回答by Zooba
The best way I have found is to use the VB function FileSystem.DeleteFile
.
我发现的最好方法是使用 VB 函数FileSystem.DeleteFile
。
It requires adding Microsoft.VisualBasic
as a reference, but this is part of the .NET framework and so isn't an extra dependency.
它需要添加Microsoft.VisualBasic
作为参考,但这是 .NET 框架的一部分,因此不是额外的依赖项。
Alternate solutions require a P/Invoke to SHFileOperation, as well as defining all the various structures/constants. Including Microsoft.VisualBasic
is much neater by comparison.
替代解决方案需要 P/Invoke 到SHFileOperation,以及定义所有各种结构/常量。Microsoft.VisualBasic
相比之下,包括更整洁。