NEWS

[C#] Hướng dẫn viết ứng dụng liệt kê thông tin, xóa và khôi phục file và folder trong Recycle Bin Windows

[C#] Hướng dẫn viết ứng dụng liệt kê thông tin, xóa và khôi phục file và folder trong Recycle Bin Windows
Đăng bởi: Thảo Meo - Lượt xem: 8747 23:36:02, 10/08/2018DEVEXPRESS   In bài viết

Xin chào các bạn, bài viết hôm nay mình sẽ hướng dẫn các bạn làm việc với Recycle Bin trong lập trình C#, với các chức năng như hiển thị thông tin file và folder, xóa file, và khôi phục file trong thùng rác windows.

- Trong bài viết này, để thao tác với Recycle Bin, các bạn cần import thư viện Shell32.dll của windows

Thư viện Shell32.dll nằm trong thư mục C:WindowsSystem32Shell32.dll

Dưới đây là giao diện demo ứng dụng làm việc với Recycle Bin C#:

khôi phục file trong recycle bin c#

Video demo ứng dụng:

Đầu tiên các bạn cần import thư viện vào:

using Shell32;

1. Tạo một class ReycleBin Item chứa các thông tin như: FileName, RecyclebinPath, OriginPath, FileType, FilleSize, ModifyDate của tập tin và folder

        public class RecycleBinItem

        {

            public string FileName { get; set; }
            public string RecycleBinPath { get; set; }
            public string OriginPath { get; set; }

            public string FileType { get; set; }

            public string FileSize { get; set; }
            public string ModifyDate { get; set; }

        }

2. Viết hàm lấy thông tin của tất cả các file trong Recycle Bin trả về đối tượng List RecycleBinItem

public List GetRecycleBinItems()
{
    try
    {
        Shell shell = new Shell();
        List list = new List();
        Folder recycleBin = shell.NameSpace(10);
        foreach (FolderItem2 f in recycleBin.Items())
            list.Add(
                    new RecycleBinItem
                    {
                        FileName = f.Name,
                        FileType = f.Type,
                        FileSize = convert.ToPrettySize(GetSize(f)),
                        ModifyDate = f.ModifyDate.ToString("dd/MM/yyyy HH:mm:ss"),
                        OriginPath = recycleBin.GetDetailsOf(f, 1),
                        RecycleBinPath = f.Path


    });
        Marshal.FinalReleaseComObject(shell);
        return list;
    }
    catch (Exception ex)
    {
        MessageBox.Show(string.Format("Error accessing the Recycle Bin: {0}", ex.Message));
        return null;
    }
}

3. Viết hàm lấy kích thước file trong recycle bin

public double GetSize(FolderItem folderItem)
{
    if (!folderItem.IsFolder)
        return (double)folderItem.Size;
    Folder folder = (Folder)folderItem.GetFolder;
    double size = 0;
    foreach (FolderItem2 f in folder.Items())
        size += GetSize(f);
    return size;
}

4. Viết một class convert để chuyển đổi byte sang KB, MB, GB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ListFileAndDirectoryRecycleBin
{
    public static class  convert
    {
        private const long OneKb = 1024;
        private const long OneMb = OneKb * 1024;
        private const long OneGb = OneMb * 1024;
        private const long OneTb = OneGb * 1024;

        public static string ToPrettySize(this double value, int decimalPlaces = 0)
        {
            var asTb = Math.Round((double)value / OneTb, decimalPlaces);
            var asGb = Math.Round((double)value / OneGb, decimalPlaces);
            var asMb = Math.Round((double)value / OneMb, decimalPlaces);
            var asKb = Math.Round((double)value / OneKb, decimalPlaces);
            string chosenValue = asTb > 1 ? string.Format("{0}Tb", asTb)
                : asGb > 1 ? string.Format("{0} Gb", asGb)
                : asMb > 1 ? string.Format("{0} Mb", asMb)
                : asKb > 1 ? string.Format("{0} Kb", asKb)
                : string.Format("{0} byte", Math.Round((double)value, decimalPlaces));
            return chosenValue;
        }
    }
}

5. Viết hàm ListFileAndFolderRecycleBin() để lấy thông tin file hiển thị vào ListView

public void ListFileAndFolderRecycleBin()
{
    
    var recycleBinItems = GetRecycleBinItems();
    listView1.Items.Clear();
    foreach (var item in recycleBinItems)
    {
        ListViewItem lvItem = new ListViewItem(new string[] { item.FileName, item.OriginPath, item.FileType, item.FileSize,  item.ModifyDate,  item.RecycleBinPath});
        listView1.Items.AddRange(new ListViewItem[] { lvItem });
    }
   

}

6. Viết sự kiện cho nút load danh sách file và thư  mục

private void button1_Click(object sender, EventArgs e)
{
    ListFileAndFolderRecycleBin();
}

7. Viết sự kiện cho nút Xóa file

private void button2_Click(object sender, EventArgs e)
{
    if (listView1.SelectedItems.Count == 0)
    {
        MessageBox.Show("Vui lòng chọn dòng dữ liệu để xóa!", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Error);           
        return;
    }             

    ListViewItem item = listView1.SelectedItems[0];
    if(item.SubItems[2].Text.Equals("File folder"))
    {
        // xóa folder
        if (Directory.Exists(item.SubItems[5].Text))
        {
            Directory.Delete(item.SubItems[5].Text, true);
        }
       
    }
    else
    {
        // Xóa file
        File.Delete(item.SubItems[5].Text);
    }           
    ListFileAndFolderRecycleBin();


}

8. Viết sự kiện cho nút Empty RecycleBin

private void btnEmptyRecycleBin_Click(object sender, EventArgs e)
{
    //kiểm tra thùng rác có file hay không
    ListFileAndFolderRecycleBin();
    var recycleBinItems = GetRecycleBinItems();
    if (recycleBinItems.Count > 0)
    {
        DialogResult dialogResult = MessageBox.Show( "Bạn có chắc chắn muốn xóa hết dữ liệu trong thùng rác không?", "Thông báo!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
        if (dialogResult == DialogResult.Yes)
        {
            foreach(var item in recycleBinItems)
            {
                if (item.FileType.Equals("File folder"))
                {
                    // xóa folder
                    if (Directory.Exists(item.RecycleBinPath))
                    {
                        Directory.Delete(item.RecycleBinPath, true);
                    }
                }
                else
                {
                    //Xóa file
                    File.Delete(item.RecycleBinPath);
                }
            }
            ListFileAndFolderRecycleBin();
        }
        
    }
    else
    {
        MessageBox.Show("Không có tập tin hay thư mục nào trong thùng rác!", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }            
}

9. Viết sự kiện cho nút khôi phục file và tập tin

//khôi phục tập tin hoặc thư mục
private bool Restore(string Item)
{
    var Shl = new Shell();
    Folder Recycler = Shl.NameSpace(10);
    for (int i = 0; i < Recycler.Items().Count; i++)
    {
        FolderItem FI = Recycler.Items().Item(i);
        string FileName = Recycler.GetDetailsOf(FI, 0);
        if (Path.GetExtension(FileName) == "") FileName += Path.GetExtension(FI.Path);
        //Necessary for systems with hidden file extensions.
        string FilePath = Recycler.GetDetailsOf(FI, 1);
        if (Item == Path.Combine(FilePath, FileName))
        {
            DoVerb(FI, "ESTORE");
            return true;
        }
    }
    return false;
}
private bool DoVerb(FolderItem Item, string Verb)
{
    foreach (FolderItemVerb FIVerb in Item.Verbs())
    {
        if (FIVerb.Name.ToUpper().Contains(Verb.ToUpper()))
        {
            FIVerb.DoIt();
            return true;
        }
    }
    return false;
}

private void btn_Restore_Click(object sender, EventArgs e)
{
    if (listView1.SelectedItems.Count == 0)
    {
        MessageBox.Show("Vui lòng chọn dòng dữ liệu để khôi phục!", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    }

    ListViewItem item = listView1.SelectedItems[0];
    Restore(item.SubItems[1].Text + "\" + item.SubItems[0].Text + Path.GetExtension(item.SubItems[5].Text));
    ListFileAndFolderRecycleBin();
}

Lưu ý: Khi xóa tập tin thì phần mềm chạy được, nhưng khi xóa folder thì nó báo không có quyền truy cập, các bạn có thể đọc bài empty recycle bin trong bài viết của mình để tham khảo.

Do mình chưa có thời gian nên chưa nghiên cứu, bạn nào làm được thì chia sẽ lại giùm mình nhé.

Source code bên dưới mình viết bằng Visual Studio 2017.

HAPPY CODING heart

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn viết ứng dụng liệt kê thông tin, xóa và khôi phục file và folder trong Recycle Bin Windows
Đăng bởi: Thảo Meo - Lượt xem: 8747 23:36:02, 10/08/2018DEVEXPRESS   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.