开发者

How can I opt the user to delete all files in a folder (but no subdirectories)?

开发者 https://www.devze.com 2022-12-21 02:54 出处:网络
I\'ve got a folder path. The folder contains a lot of files as well 开发者_JAVA百科as some subfolders. I\'d like to let the user delete the files (but not the folders) using the standard windows dialo

I've got a folder path. The folder contains a lot of files as well 开发者_JAVA百科as some subfolders. I'd like to let the user delete the files (but not the folders) using the standard windows dialog.

I'm currently using this code, which deletes the whole folder.

Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory (
    path,
    UIOption.AllDialogs,
    RecycleOption.SendToRecycleBin,
    UICancelOption.DoNothing);

I'm aware I could enumerate all files and prompt the user for each file, but that's not practical at all.


Why not just write a function for this specific task?

public static void DeleteFilesInFolder()
        {
            using(var dlg = new FolderBrowserDialog())
            {
                if(dlg.ShowDialog() == DialogResult.OK)
                {
                    var folderPath = dlg.SelectedPath;
                    var dir = new DirectoryInfo(folderPath);
                    var files =dir.GetFiles();
                    foreach (var f in files)
                {
                    try
                    {
                        f.Delete();
                    }
                    catch (Exception ex) {
                        //handle this error
                    }
                }
                }
            }
        }

ah ok, just a suggestion..

then have a look at this:

http://www.blackwasp.co.uk/RecycleBin2.aspx

[StructLayout(LayoutKind.Sequential)]
public struct SHFILEOPSTRUCT
{
    public IntPtr hwnd;
    public uint wFunc;
    public string pFrom;
    public string pTo;
    public ushort fFlags;
    public int fAnyOperationsAborted;
    public IntPtr hNameMappings;
    [MarshalAs(UnmanagedType.LPWStr)]
    public string lpszProgressTitle; 
}

private const int FO_DELETE = 0x0003;
private const int FOF_SILENT = 0x0004;
private const int FOF_ALLOWUNDO = 0x0040;
private const int FOF_NOCONFIRMATION = 0x0010;
private const int FOF_WANTNUKEWARNING = 0x4000;

[DllImport("Shell32.dll")]
static extern int SHFileOperation([In] ref SHFILEOPSTRUCT lpFileOp);

used like this to delete all files matching the *.* pattern in a folder:

SHFILEOPSTRUCT operation = new SHFILEOPSTRUCT();
operation.wFunc = FO_DELETE;
operation.pFrom = @"c:\Recycle\*.*" + "\0\0";
operation.fFlags = FOF_ALLOWUNDO;
int result = SHFileOperation(ref operation);


Visual Basic uses the SHFileOperation() API function to display the dialog. I think you can call it yourself and customize it the way you want by specifying the FOF_FILESONLY flag for the SHFILEOPSTRUCT.fFlags member. The P/Invoke is gritty, visit pinvoke.net for the declarations.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号