要如何透過參考shell32.dll來取得資源回收筒RecycleBin的檔案資訊呢?
有朋友問「C# 如何获取到回收站里面的文件信息」。
查到「Working With The Windows Recycle Bin With C#」,可直接透過C:\windows\system32\shell32.dll來操作。
1.建立專案
2.在專案中加入 C:\windows\system32\shell32.dll 參考
3.建立RecycleBinItem及RecycleBin類別(加入using Shell32;),如下,
public class RecycleBinItem
{
public string FileName { get; set; }
public string FileType { get; set; }
public string FileSize { get; set; }
}
public class RecycleBin
{
public List<RecycleBinItem> GetRecycleBinItems()
{
try
{
//create a new isntance of the Shell32 interface
Shell shell = new Shell();
List<RecycleBinItem> list = new List<RecycleBinItem>();
//create a folder item to our Recycle Bin
Folder recycleBin = shell.NameSpace(10);
//now let's loop through all the Items in our Folder object
//and add them to a generic list
foreach (FolderItem2 f in recycleBin.Items())
list.Add(
new RecycleBinItem
{
FileName = f.Name,
FileType = f.Type,
FileSize = GetSize(f).ToString()
});
//return the list
return list;
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Error accessing the Recycle Bin: {0}", ex.Message));
return null;
}
}
public double GetSize(FolderItem folderItem)
{
//check if it's a folder, if it's not then return it's size
if (!folderItem.IsFolder)
return (double)folderItem.Size;
//create a new Shell32.Folder item
Folder folder = (Folder)folderItem.GetFolder;
double size = 0;
//since we're here we're dealing with a folder, so now we will loop
//through everything in it and get it's size, thus calculating the
//overall size of the folder
foreach (FolderItem2 f in folder.Items())
size += GetSize(f);
//return the size
return size;
}
}
4.操作方式如下(如果是Console程式的話,請加入[STAThread]),
[STAThread]
static void Main(string[] args)
{
RecycleBin bin = new RecycleBin();
var items = bin.GetRecycleBinItems();
foreach (RecycleBinItem item in items)
Console.WriteLine(string.Format("File: {0} => Size: {1} => Type: {2}",
item.FileName, item.FileSize, item.FileType));
Console.ReadLine();
}
參考資訊
Working With The Windows Recycle Bin With C#
Instantiate Shell32.Shell object in Windows 8
Hi,
亂馬客Blog已移到了 「亂馬客 : Re:從零開始的軟體開發生活」
請大家繼續支持 ^_^