To ng dng Duyt File và thư mc đơn gin vi C Sharp
Bài viết này gii thiu cách ly các thông tin ca các
đĩa h thng và cách ly thông tin v các thư mc và File
để phân b vào các điu khin Treeview và listview. Đây
là mt ng dng đơn gin ca WinForm.
Trước hết, ta cn thu thp tt c các thông tin v tt c
các đĩa trong My Computer mà chúng ta có th truy
cp vào và hin th tên là loi trong điu khin
Treeview. Chúng ta có th truy vn thông qua
lp ManagementObjectSearcher trong không gian tên
System.Management. Nó chp nhn các câu lnh SQL
Như thc hin các câu truy vn và tr v mt đối tượng
ManagementOjbectCollection mà cha tt c các thông tin v đĩa mà chúng ta yêu cu. bây
gi chúng ta đã có tt c các thông tin v đĩa như: Tên đĩa, Loi, các mô t... Ta viết hàm
GetDrivers() để thc thi mc đích đó:
protected ManagementObjectCollection GetDrivers()
{
ManagementObjectSearcher query = new ManagementObjectSearcher("Select * From
Win32_LogicalDisk");
ManagementObjectCollection queryCollection = query.Get();
return queryCollection;
}
Khi ng dng được np lên chúng ta cn phi tìm tt c các đĩa có trong My Computer và hin
th chúng.
private void PopulateDriveList()
{
TreeNode nodeTreeNode;
int imageIndex = 0;
int selectIndex = 0;
const int Removable = 2;
const int LocalDisk = 3;
const int Network = 4;
const int CD = 5;
this.Cursor = Cursors.WaitCursor;
// Xóa Treeview
tvFolders.Nodes.Clear();
nodeTreeNode = new TreeNode("My Computer", 0, 0);
tvFolders.Nodes.Add(nodeTreeNode);
// Thiết lp tp hp các Node
TreeNodeCollection nodeCollection = nodeTreeNode.Nodes;
// Ly danh sách các đĩa
ManagementObjectCollection queryCollection = GetDrivers();
foreach (ManagementObject mo in queryCollection)
{
switch (int.Parse(mo["DriveType"].ToString()))
{
case Removable: // Các Đĩa Mm
imageIndex = 5;
selectIndex = 5;
break;
case LocalDisk: // Các Đĩa Cng
imageIndex = 6;
selectIndex = 6;
break;
case CD: // Các Đĩa CD
imageIndex = 7;
selectIndex = 7;
break;
case Network: // Các Liên Kết qua mng
imageIndex = 8;
selectIndex = 8;
break;
default:
imageIndex = 2;
selectIndex = 3;
break;
}
// To mt Driver Node mi
nodeTreeNode = new TreeNode(mo["Name"].ToString() + "\\", imageIndex,
selectIndex);
// Chèn vào Treeview
nodeCollection.Add(nodeTreeNode);
}
InitListView();
this.Cursor = Cursors.Default;
}
Và khi to mt Listview để hin th các thông tin v File trong Hàm InitListView():
protected void InitListView()
{
// Khi to Listview ban đầu
lvFiles.Clear();
//// To các header cho Listview
lvFiles.Columns.Add("Tên File", 140, HorizontalAlignment.Left);
lvFiles.Columns.Add("Dung Lượng", 75, HorizontalAlignment.Right);
lvFiles.Columns.Add("Ngày To", 140, HorizontalAlignment.Right);
lvFiles.Columns.Add("Ngày Sa", 140, HorizontalAlignment.Right);
}
Khi chúng ta chn mt đĩa hoc 1 thư mc trong Treeview, chúng ta cn kim tra xem đĩa
hay thư mc đó có tn ti hay không trước khi thc hin các thao tác khác. Sau khi kim tra s
tn ti ca các thư mc trong đĩa, ta ly tt c các thư mc tn ti khi chn mt đĩa trong
Treeview bng cách s dng lp Directory trong không gian tên System.IO. Gi hàm
Directory.GetDirectories vi tham sđường dn ca Node hin thi và tr v mt mng các
thư mc. chúng ta duyt tt c các thư mc trong mng này và phân b chúng vào các Node con.
Hàm x lý s kin nhn và Treeview như sau:
private void tvFolders_AfterSelect(object sender, TreeViewEventArgs e)
{
// Phân b thư mc hoc File khi mt thư mc được chn
this.Cursor = Cursors.WaitCursor;
// Ly đĩa hoc thư mc đang được la chn
TreeNode currentNode = e.Node;
// Xóa toàn b thư mc con
currentNode.Nodes.Clear();
if (currentNode.SelectedImageIndex == 0)
{
// My Computer được chn - Phân b li danh sách các đĩa.
PopulateDriveList();
}
else
{
// Phân b các thư mc con và các File.
PopulateDirectory(currentNode, currentNode.Nodes);
}
this.Cursor = Cursors.Default;
}
Chúng ta kim tra xem Mc My Computer đã được m rng hay chưa? nếu chưa thì ta phi gi
hàm để phân b danh sách các đĩa. Còn ngược li, ta duyt tiếp các thư mc cp độ nh hơn
bng hàm PopulateDirectory(currentNode, currentNode.Nodes):
protected void PopulateDirectory(TreeNode currentNode, TreeNodeCollection
currentNodeCollection)
{
TreeNode nodeDir;
int imageIndex = 2; // Ch mc nh khi không được chn
int selectIndex = 3; // Ch mc nh khi được chn.
if (currentNode.SelectedImageIndex != 0)
{
// phân b các thư mc trong Treeview
try
{
// Kim tra đường dn
if (Directory.Exists(GetFullPath(currentNode.FullPath)) == false)
{
MessageBox.Show(" đĩa hoc thư mc " + currentNode.ToString() + " Không
tn ti");
}
else
{
//Phân b các Files.
PopulateFiles(currentNode);
string[] stringDirectories =
Directory.GetDirectories(GetFullPath(currentNode.FullPath));
string stringFullPath = "";
string stringPathName = "";
// Lp qua tt c các thư mc
foreach (string stringDir in stringDirectories)
{
stringFullPath = stringDir;
stringPathName = GetPathName(stringDir);
// To các Node cho thư mc
nodeDir = new TreeNode(stringPathName.ToString(), imageIndex,
selectIndex);
currentNodeCollection.Add(nodeDir);
}
}
}
catch (IOException e)
{
MessageBox.Show("Li: đĩa không có hoc thư mc không tn ti.");
}
catch (UnauthorizedAccessException e)
{
MessageBox.Show("Li: Bn không có quyn truy cp vào đĩa hoc thư mc
này");
}
catch (Exception e)
{
MessageBox.Show("Li " + e);
}
}
}
Đến bước này, chúng ta va duyt các thư mc con và hin th các File ra Listview. Chúng ta
viết Hàm PopulateFiles(TreeNode currentNode) để thc hin điu này. Trong đó ta có s dng
hàm Directory.GetFiles vi tham sđường dn ca Node hin thi. hàm này s tr v mt
mng các File trong đĩa hoc thư mc la chn. Ta duyt qua tt c các phn t mng và phân
b vào Listview. Lp FileInfo ly các thông tin chi tiết v File như Dung lượng, ngày to, ngày
sa đổi...
protected void PopulateFiles(TreeNode currentNode)
{
string[] lvData = new string[4];
InitListView();
if (currentNode.SelectedImageIndex != 0)
{
// Kim tra đường dn
if (Directory.Exists(GetFullPath(currentNode.FullPath)) == false)
{
MessageBox.Show("Thư mc hoc đường dn" + currentNode.ToString() + "Không
tn ti");
}
else
{
try
{
string[] stringFiles = Directory.GetFiles(GetFullPath(currentNode.FullPath));
string stringFileName = null;
DateTime dtCreateDate, dtModifyDate;
Int64 lFileSize = 0;
// Duyt tt c các File.