之前在c++上遇到过这个问题,折腾许久才解决了,这次在c#上再次遇到这个问题,不过似乎容易了一些,亲测代码如下,两种删除方式都写在代码中了。

直接上完整代码:
using microsoft.visualbasic.fileio;
using system;
using system.io;
using system.runtime.interopservices;
namespace ceshiconsole
{
public class fileiohelper
{
[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;
}
#region dllimport
[dllimport("shell32.dll", charset = charset.auto)]
public static extern int shfileoperation(ref shfileopstruct fileop);
#endregion
#region const
public const int fo_delete = 3;
public const int fof_allowundo = 0x40;
public const int fof_noconfirmation = 0x10;
#endregion
#region public static method
public static void deletefiletorecyclebin(string file, boolean showconfirmdialog = false)
{
shfileopstruct shf = new shfileopstruct();
shf.wfunc = fo_delete;
shf.fflags = fof_allowundo;
if (!showconfirmdialog)
{
shf.fflags |= fof_noconfirmation;
}
shf.pfrom = file + '\0' + '\0';
shfileoperation(ref shf);
}
public static bool sendtorecyclebin(string path)
{
bool bret = true;
try
{
if (file.exists(path))
{
filesystem.deletefile(path, uioption.onlyerrordialogs, recycleoption.sendtorecyclebin);
}
else if (directory.exists(path))
{
filesystem.deletedirectory(path, uioption.onlyerrordialogs, recycleoption.sendtorecyclebin);
}
else
{
bret = false;
}
}
catch (exception ex)
{
console.writeline($"无法将文件/目录 {path} 移动到回收站: {ex.message}");
bret = false;
}
return bret;
}
static void main(string[] args)
{
deletefiletorecyclebin(@"c:\users\autumoon\desktop\test.txt");
sendtorecyclebin(@"c:\users\autumoon\desktop\test2.txt");
}
#endregion
}
}到此这篇关于c#实现删除文件和目录到回收站的文章就介绍到这了,更多相关c#删除文件和目录内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论