chương trình quản lý file trên hệ Điều hành

60
Chương trình quản lý file trên hệ điều hành Đồ án tin học: Chương Trình Quản Lý File Trên Hệ Điều Hành 1.Tổng Quan 1.1. Giới thiệu hệ thống File Bộ nhớ nội của máy tính thường có dung lượng nhỏ, chỉ đủ chứa chương trình và dữ liệu đang được xử lý. Cần có thiết bị khác làm chỗ chứa các chương trình và dữ liệu đã/đang/sẽ xử lý, thiết bị này được gọi là bộ nhớ ngoài, nó cần có dung lượng rất lớn. Có rất nhiều kỹ thuật khác nhau để tạo ra bộ nhớ ngoài như đĩa cứng, băng, CDROM, flash ROM,... Đễgiúp user dùng các loại bộ nhớ ngoài dễ dàng, đồng nhất, HĐH sẽ trừu tượng hóa chúng thành 1 hệ thống cây phân cấp được gọi là hệ thống file. Các tính chất thiết yếu của 1 hệ thống file : Nó cần có dung lượng rất lớn để chứa rất nhiều file chương trình và dữ liệu cần dùng trên máy tính. Nội dung được lưu trên hệ thống file phải tồn tại lâu dài, ngay cả khi process tạo ra nó đã chết. Nhiều process có thể truy xuất đồng thời vào từng phần tử trên hệ thống file. Truy xuất đĩa vật lý : Disk vật lý là không gian dữ liệu 3 chiều, mỗi disk = nhiều cylinder, mỗi cylinder gồm nhiều SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 1

Upload: keery-pham

Post on 28-Jul-2015

149 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

Đồ án tin học:

Chương Trình Quản Lý File

Trên Hệ Điều Hành

1. Tổng Quan1.1. Giới thiệu hệ thống File Bộ nhớ nội của máy tính thường có dung lượng nhỏ, chỉ đủ chứa chương

trình và dữ liệu đang được xử lý. Cần có thiết bị khác làm chỗ chứa các chương trình và dữ liệu đã/đang/sẽ

xử lý, thiết bị này được gọi là bộ nhớ ngoài, nó cần có dung lượng rất lớn. Có rất nhiều kỹ thuật khác nhau để tạo ra bộ nhớ ngoài như đĩa cứng, băng, CDROM, flash ROM,...

Đễgiúp user dùng các loại bộ nhớ ngoài dễ dàng, đồng nhất, HĐH sẽ trừu tượng hóa chúng thành 1 hệ thống cây phân cấp được gọi là hệ thống file.

Các tính chất thiết yếu của 1 hệ thống file : Nó cần có dung lượng rất lớn để chứa rất nhiều file chương trình và dữ liệu cần dùng trên máy tính. Nội dung được lưu trên hệ thống file phải tồn tại lâu dài, ngay cả khi process tạo ra nó đã chết. Nhiều process có thể truy xuất đồng thời vào từng phần tử trên hệ thống file.

Truy xuất đĩa vật lý : Disk vật lý là không gian dữ liệu 3 chiều, mỗi disk = nhiều cylinder, mỗi cylinder gồm nhiều track (head - vòng tròn chứa tin) có cùng đường kính), mỗi track chứa nhiều cung chứa tin nhỏ được truy xuất độc lập nhau (sector). Sector là đơn vị truy xuất tin nhỏ nhất ở cấp vật lý (từ ngoài ta không thể truy xuất từng byte dữ liệu trên disk được). Muốn truy xuất 1 sector, ta phải xác định tọa độ 3 chiều của nó (C,H,S) → rất khó tư duy. Dữ liệu có nghĩa thường có độ lớn khác nhau và cần nhiều sector mới chứa đủ. Ở cấp vật lý này, người dùng phải tự quản lý danh sách các tọa độ sector 3 chiều được dùng để lưu trữ 1 dữ liệu có nghĩa nào đó → rất khó khăn và phiền hà → cần 1 cấp giao tiếp khác dễ sử dụng hơn.

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 1

Page 2: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

Thời gian truy xuất 1 sector đĩa vật lý = ∑ Thời gian dời đầu đọc/ghi đến cyclinder cần truy xuất (thông qua

từ 0 tới n xung tác động vào step motor). Đây là hoạt động tốn nhiều thời gian nhất. Thời gian chờ đĩa quay sector cần truy xuất về vị trí đầu đọc/ghi

(trung bình là nữa vòng quay). Thời gian truy xuất dữ liệu của sector (tốn 1/n vòng quay).

Thời gian truy xuất 1 track/cylinder đĩa vật lý = ∑ Thời gian dời đầu đọc/ghi đến cyclinder cần truy xuất (thông qua từ

0 tới n xung tác động vào step motor). Đây là hoạt động tốn nhiều thời gian nhất. Thời gian truy xuất dữ liệu của track/cylinder (tốn 1 vòng quay). So sánh những kết quã trên, ta thấy thời gian truy xuất 1 sector hay

1 track hay 1 cyclinder gồm nhiều track hầu như bằng nhau → nên truy xuất 1 lần 1 cyclinder hơn là 1 track hay 1 sector.

Truy xuất đĩa luận lý cấp 1 : Disk luận lý cấp 1 là không gian dữliệu 1 chiều, mỗi ₫ĩa = danh

sách nhiều đơn vị chứa tin có độ dài bằng nhau (cluster, block, sector luận lý). Độ dài của cluster cần độc lập với độ dài sector đĩa vật lý. Để dễ quản lý, thường ta chọn kích thước 1 cluster = 2i sector. Để truy xuất 1 cluster, ta chỉ cần xác định tọa độ1 chiều (chỉ số) của

nó (0 → n). Dữ liệu có nghĩa thường có độ lớn khác nhau và cần nhiều cluster

mới chứa đủ. Ở cấp luận lý này, người dùng phải tự quản lý danh sách các chỉ số cluster được dùng để lưu trữ 1 dữ liệu có nghĩa nào ₫ó → vẫn còn khó khăn và phiền hà → cần 1 cấp giao tiếp khác dễ sử dụng hơn.

Truy xuất đĩa luận lý cấp 2 : Disk luận lý cấp 2 là không gian dữ liệu 1 chiều, mỗi đĩa = danh

sách nhiều đơn vị chứa tin có độ dài thay đổi tùy ý theo yêu cầu của người dùng (file). Mỗi file được nhận dạng bằng tên gợi nhớ thay vì bằng chỉ số. Để dễ quản lý, thường ta sẽ dùng n cluster đĩa để lưu nội dung của 1 file. Muốn truy xuất 1 file, ta chỉ cần xác định tên gợi nhớ thay vì bằng

chỉ số của nó. dữ liệu có nghĩa thường có độ lớn khác nhau, nhưng ở cấp độ này ta chỉ cần thay đổi kích thước file cho phù hợp → rất dễ quản lý thông tin chứa trên disk. Thường disk có dung lượng rất lớn và chứa rất nhiều file dữ liệu

nên việc đặt tên file dễ tranh chấp nhau, hơn nữa việc quản lý file sẽ gặp

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 2

Page 3: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

nhiều khó khăn (xóa/tạo mới, xác định file nào cần truy xuất,..) → cần 1 cấp giao tiếp khác dễ sử dụng hơn.

Truy xuất đĩa luận lý cấp 3 : Disk luận lý cấp 3 là không gian dữ liệu dạng cây phân cấp, mỗi đĩa

= thư mục gốc chứa nhiều phần tử con, mỗi phần tử con có thể là file hoặc thư mục... Muốn truy xuất 1 file/thư mục, ta chỉ cần dùng pathname. có 2 loại pathname : tuyệt đối và tương đối. Pathname tuyệt đối sẽ

xuất phát từ thư mục gốc để tìm phần tử cần truy xuất. Pathname tương đối xuất phát từ thư mục hiện hành (working) để tìm phần tử cần truy xuất. Tùy thuộc vào ngữ cảnh cụ thể mà loại pathname nào thích hợp hơn.

1.2. Giao tiếp sử dụng phân hệ quản lý File Tên file : dùng để nhận dạng file cần truy xuất. Các định dạng được dùng

phổ biến là 8.3 và chuỗi ký tự bất kỳ <= 256 ký tự.

Cấu trúc file (cấp HĐH) : có 3 cấu trúc phổ biến : a. danh sách các byte chưa có nghĩa; b.danh sách các record ngữ nghĩa xác định; c. cây các record ngữ nghĩa xác định.

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 3

Page 4: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

Cấu trúc ngữ nghĩa của file : do mỗi ứng dụng tự quy định, thường là 1 tập các record thông tin có liên quan nhau.

Cơ chế truy xuất file : Truy xuất tuần tự (Sequential access) : đọc/ghi các byte/record từ

đầu, không thể nhảy cóc. Truy xuất trực tiếp (Random access) : có thể dời đầu đọc/ghi đến

bất kỳ vị trí nào trước khi đọc/ghi dữ liệu. Thuộc tính file : mỗi file có 1 tập các thuộc tính khác nhau để HĐH quản

lý và kiểm soát việc truy xuất file của người dùng.

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 4

Page 5: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

Các hàm API truy xuất file : HĐH cung cấp 1 tập các hàm chức năng phục vụ việc truy xuất file bởi ứng dụng.

Truy xuất nội dung file : gồm 3 bướco Mở/Tạo mới file :

CreateFile : tạo mới 1 fileOpenFile : mở/tạo mới 1 file để truy xuất

o Truy xuất nội dung file :

Read : đọc n byte nội dung từ vị trí truy xuất hiện hànhWrite : ghi n byte nội dung từ vị trí truy xuất hiện hànhAppend : ghi thêm n byte vào đuôi fileSeek : dời vị trí truy xuất file về vị trí xác định

o Đóng file :

Delete : xóa file đang tồn tạiClose : đóng file và không cho phép truy xuất nữa

Truy xuất các thuộc tính file : o Get attributes : đọc các thuộc tính của file.

o Set Attributes : thiết lập lại các thuộc tính file.

o Rename : đặt lại tên file

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 5

Page 6: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

1.3. Giao tiếp sử dụng phân hệ quản lý thư mục Hệ thống file dùng thư mục 1 cấp :

Thiết bị chứa tin được trừu tượng thành 1 cây với 1 thư mục gốc. Tất cả các file ₫ều ₫ược chứa trực tiếp vào thư mục gốc, không có

thư mục con nào cả. Dạng thư mục 1 cấp rất thích hợp cho các thiết bịchứa tin có dung

lượng nhỏ như đĩa mềm...

Hệ thống file dùng thư mục 2 cấp : Thiết bị chứa tin được trừu tượng thành 1 cây với 1 thư mục gốc. Thư mục gốc chứa nhiều thư mục con (cấp 2). Mỗi thư mục con cấp 2 chỉchứa 1 sốfile chứkhông chứa thư mục con nào cả. Dạng thư mục 2 cấp rất thích hợp cho các thiết bị chứa tin có dung lượng trung bình như đĩa flash ROM, USB,...

Hệ thống file dùng thư mục n cấp : Thiết bịchứa tin ₫ược trừu tượng thành 1 cây với 1 thư mục gốc. Thư

mục gốc chứa nhiều thư mục con (cấp 2) và nhiều file. Mỗi thư mục con lại chứa 1 sốfile & 1 số thư mục con khác...

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 6

Page 7: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

Dạng thư mục n cấp rất thích hợp cho các thiết bị chứa tin có dung lượng lớn như đĩa cứng...

Hệ thống file dùng đồ thị thư mục n cấp : Thiết bị chứa tin được trừu tượng thành 1 đồ thị với 1 thư mục gốc. Thư mục gốc chứa nhiều thư mục con (cấp 2) và nhiều file. Mỗi thư mục con lại chứa 1 số file & 1 số thư mục con khác. Thư mục con của 1 thư mục có thể là thư mục mới hay thư mục đã có sẵn... Dạng đồ thị thư mục rất thích hợp trong trường hợp quản lý các thư mục dùng chung...

Pathname :

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 7

Page 8: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

Pathname tương đối được chuyển thành pathname tuyệt đối trước khi xử lý tiếp. Hệ điều hành sẽ đọc lần lượt các thư mục trong pathname tuyệt đối, bắt đầu từ thư mục gốc, để dò lần ra phần tử cần truy xuất.

Các hàm API truy xuất thư mục : Hệ điều hành cung cấp 1 tập các hàm chức năng phục vụ việc truy xuất thư mục bởi ứng dụng. Duyệt đọc nội dung thư mục :

o FindFirst : đọc record chứa thông tin quản lý phần tử đầu tiên trong

thư mục.o FindNext : đọc record chứa thông tin quản lý phần tử kế tiếp trong

thư mục. Hiệu chỉnh nội dung thư mục : 1 cách gián tiếp thông qua các lệnh sau :

o Rename, create, delete, link, unlink, move file hay thư mục con.

o Set_attributes file hay thư mục con...

1.4. Hiện thực File File = danh sách đặc các cluster liên tiếp trên đĩa. Để quản lý 1 file, ta chỉ cần cặp thông số : (chỉ số cluster đầu file, số cluster cần dùng) Rất bất tiện khi cần nới rộng kích thước file.

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 8

Page 9: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

File = danh sách liên kết các cluster bất kỳ trên đĩa. Truy xuất các cluster nội dung file theo cơ chế tuần tự → rất chậm, nhất là các dữ liệu nằm ở các cluster cuối của file lớn. Kích thước phần chứa dữ liệu trong cluster bị xé lẻ → khó tính toán và xác định vị trí dữ liệu cần truy xuất.

File = danh sách liên kết các cluster bất kỳ trên đĩa dùng FAT.

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 9

Page 10: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

Tách phần link trong các cluster và tập hợp chúng thành 1 bảng, ta gọi� bảng này là FAT (File Allocation Table). Số lượng phần tử trong bảng FAT = số cluster trên partition tương ứng, mỗi phần tử chứa pointer (dạng chỉsố) đến cluster đi ngay sau luận lý nó trong file. Có nhiều loại FAT : FAT12, FAT16, FAT32. Fat i chứa maximum 2i phần tử, mỗi phần tử dài i bit. Thí dụ FAT32 chứa tối đa 232 phần tử, mỗi phần tử dài 32 bit, miêu tả chỉsố cluster từ 0 — 232-1. Nếu Hệ Điều Hành nạp toàn bộ bảng FAT vào RAM thì việc truy xuất dữ liệu của các file là trực tiếp (giải quyết được khuyết điểm 1 của danh sách liên kết). Mỗi cluster dữ liệu chỉ chứa dữ liệu → kích thước chẵn (giải quyết được khuyết điểm 2 của danh sách liên kết). Thực tế cần dung hòa giữa dung lượng RAM dành cho FAT và hiệu quả truy xuất file → nạp từng ‘window’ của FAT vào RAM khi cần thiết. Nếu ta biết file A có cluster đầu là 4, dựa vào bảng FAT bên phải ta sẽ tìm được các cluster còn lại của file A là 7, 2, 10, 12. Tương tự, nếu ta biết file B có cluster đầu là 6, dựa vào bảng FAT bên phải ta sẽ tìm được các cluster còn lại của file B là 3, 11, 14.

Kích thước cluster và partition dùng FAT :

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 10

Page 11: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

File = danh sách liên kết các cluster trên đĩa dùng bảng chỉ số. Tập hợp các phần link trong các cluster của từng file thành 1 bảng chỉ số� cho file đó. Bảng này được chứa trong 1 cấu trúc quản lý file (i-node trên Unix). Do kích thước các file rất khác nhau nên bảng chỉ số dài ngắn khác nhau → gây khó khăn trong việc quản lý → Unix dùng bảng chỉ số nhiều cấp :o 10 phần tử đầu chứa chỉ số các cluster dữ liệu.

o 1 phần tử chỉ số đến cluster chứa các chỉ số các cluster dữ liệu (C11).

o 1 phần tử chỉ số đến cluster chứa các chỉ số các cluster C11 (C12).

o 1 phần tử chỉ số đến cluster chứa các chỉ số các cluster C12 (C13).

Mỗi khi cần truy xuất file, Hệ Điều Hành nạp i-node của file vào RAM →� việc truy xuất dữ liệu của file là trực tiếp. Mỗi cluster dữliệu chỉchứa dữliệu → kích thước chẵn (giải quyết được khuyết điểm 2 của danh sách liên kết).

1.5. Hiện thực thư mục

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 11

Page 12: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

Thư mục = file (gồm nhiều cluster đĩa). Cấu trúc ngữ nghĩa của thư mục = danh sách đặc các record, mỗi record (entry) quản lý thông tin của 1 phần tử con, gồm 2 thành phần chính : tên gợi nhớ của phần tử, các thuộc tính quản lý phần tử. Hình a. : tất cảcác thuộc tính quản lý phần tử ₫ều ₫ược ₫ể trong entry thư mục (FAT). Hình b. : entry thư mục chỉ chứa chỉ số i-node, i-node mới là record chứa các thuộc tính quản lý phần tử (Unix).

Cấu trúc entry thư mục của chuẩn ISO9660 (CDROM).

Cấu trúc entry thư mục trên HĐH CP/M.

Cấu trúc entry thư mục của FAT16 (Microsoft).

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 12

Page 13: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

Dùng i-node để quản lý các thuộc tính của file/thư mục rất thích hợp cho việc dùng chung file/thư mục: File F là file dùng chung cho 2 thư mục B và C.

1.6. Quản lý các cluster chưa dung Tại từng thời điểm, mỗi cluster thuộc 1 trong 2 trạng thái sau : Đã dùng, cluster này phải thuộc về1 file nào ₫ó →truy xuất file đó ta sẽ� tìm được cluster này. Chưa dùng nên chưa thuộc file nào cả → cần có cơ chế quản lý các cluster này.

Dùng bảng trạng thái

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 13

Page 14: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

Bảng trạng thái có N phần tử (N :� sốcluster của partition), mỗi phần tử là 1 bit nhị phân, nếu = 0 thì cluster tương ứng chưa dùng, nếu = 1 thì cluster tương ứng đã dùng rồi bởi file nào đó. Khi ứng dụng xin cấp phát 1 cluster, Hệ Điều Hành sẽ dò tuần tự trong bảng trạng thái để tìm 1 phần tử(chỉ số i) = 0 → cluster i chưa dùng. Việc dò tuần tự là không hiệu quả, ngay cả có cải tiến bằng cách lưu giữ vị trí đã dò tìm lần cuối để mỗi khi tìm cluster chưa dùng, ta chỉ dò từ vị trí lưu giữ chứ không phải dò từ đầu bảng.

Dùng danh sách liên kết các cluster chưa dùng

Danh sách chỉ chứa các cluster chưa dùng. Khi ứng dụng xin cấp phát 1 cluster, Hệ Điều Hành sẽ lấy ngay cluster ở đầu danh sách rồi hiệu chỉnh lại đầu danh sách mới. Tốn nhiều bộ nhớ cho danh sách liên kết, nhất là lúc partition mới format, chưa có file nào cả.

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 14

Page 15: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

Tính nhất quán của hệ thống file Về ý nghĩa, tại từng thời điểm, mỗi cluster hoặc thuộc 1 file nào đó hoặc chưa dùng và được quản lý trong danh sách cluster chưa dùng Hệ thống file được gọi là đang nhất quán nếu từng cluster trong hệ thống thỏa mãn điều kiện nêu trên.

Hệ thống bị mất tính nhất quán khi 1 trong các điều kiện sau đã xảy ra : 1 cluster ₫ược dùng bởi nhiều hơn 1 file. 1 cluster ₫ược dùng bởi 1 file nhưng vẫn xuất hiện trong danh sách cluster chưa dùng. 1 cluster không thuộc file nào nhưng tồn tại nhiều lần trong danh sách các cluster chưa dùng. 1 cluster không thuộc file nào và không xuất hiện trong danh sách các cluster chưa dùng.

Trình phát hiện mất tính nhất quán của hệ thống file và chữa trị (scandisk) Dùng 2 cấu trúc dữ liệu chính yếu :o used[N], trong đó used[i] = số file sử dụng cluster i (thường là 0 hay 1).

o noused[N], trong đó noused[i] = số lần cluster i xuất hiện trong danh

sách cluster chưa dùng (thường là 0 hay 1 ). Khởi động giá trị ban đầu của 2 cấu trúc dữ liệu :

for (i =0; i <N; i++) used[i] = noused[i] = 0; Xây dựng vector used[N] bằng cách duyệt đệ quy hệ thống file từ thư mục gốc, mỗi lần gặp 1 file/thư mục, ta duyệt từng cluster được nó sử dụng, mỗi lần gặp cluster i, ta thực hiện used[i]++. Xây dựng vector noused[N] bằng cách duyệt danh sách các cluster chưa dùng, mỗi lần gặp cluster i, ta thực hiện noused[i]++.

2. Xây dựng chương trình

Đề tài nghiên cứu về việc quản lý ổ đĩa, thư mục trên hệ điều hành nhằm để truy xuất các file khác nhau, tùy theo mục đích sử dụng của người đối với hệ thống mà ta có thể thực hiện được các chức năng cơ bản như:

Cấu trúc thư mục, tìm kiếm file và folder hiện diện và kiểm tra thuộc tính của chúng.

Di chuyển, sao chép, xóa, đổi tên các file và folder. Tìm kiếm các file và folder có trong hệ thống. Cho biết thông tin về các file có trong hệ thống như: loại file, kích

thước, thời gian sửa đổi ần cuối.

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 15

Page 16: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

Chương trình được thiết kế trên Giao diện của Windown Form gồm một form chính và 2 form con và 4 lớp thuộc form chính nhằm phục vụ truy xuất trực tiếp trên giao diện sử dụng, sử dụng các tài nguyên trong thư viện được xây dựng sắn trong phần mềm Visual Basic 2008 . Trong đó, chương trình sử dụng các code có trong không gian IO (System.IO, System Text, System Data ….), sử dụng các tác vụ, công cụ như: TextBox, Button, ListBox, PictureBox, GroupBox… . Ngoài ra chương trình sử dụng các lệnh trực tiếp để gọi các form con.

2.1. Sử dụng thư viện hệ thống của Visual Basic 2008

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using Windows_Explorer.Class;using System.IO;using System.Collections;using System.Windows.Forms.Design;using Microsoft.VisualBasic.FileIO;

2.2. Giao diện chính của chương trình

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 16

Page 17: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

2.3. Xây dựng chương trình

Gọi các lớp vào form chính

clsTreeView cls = new clsTreeView(); clsItem clsitem = new clsItem();

clsHistory History = new clsHistory();

Chương trình hiển thị thông tin của file, folder, ổ đĩa lên cây thư mục và cây tệp tin.

private void frmMain_Load(object sender, EventArgs e) { Back = new ArrayList(); Forward = new ArrayList(); Class.clsTreeView.CreateTreeView(tvTreeView); TreeNode tn = new TreeNode(); foreach (DriveInfo drvi in DriveInfo.GetDrives()) { TreeNode tndrv = new TreeNode(); if (drvi.DriveType == DriveType.CDRom) { tndrv.Text = "CD Drive(" + drvi.Name + ")"; cdrom = tndrv.Text; } else { tndrv.Text = " " + drvi.Name; } tn.Nodes.Add(tndrv); } for (int i = 0; i < tn.Nodes.Count; i++) { cboPath.Items.Add(tn.Nodes[i].Text.ToString()); }

}

private void tvTreeView_AfterSelect(object sender, TreeViewEventArgs e) { try { cls.OpenFolder(e.Node, lvListView); if (e.Node.Text.Equals("My Computer") && e.Node.Parent.Text == "Desktop") cboPath.Text = "My Computer"; else cboPath.Text = cls.Path; Program.fmain.Text = e.Node.Text; cls.HistoryAdd();

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 17

Page 18: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

Back.Add(e.Node); statusLabel1.Text = lvListView.Items.Count.ToString() + " object(s)"; History.InSertBack_DropDownbutton(e.Node); } catch { }

}

private void lvListView_MouseDoubleClick(object sender, MouseEventArgs e) { ListViewItem item = lvListView.FocusedItem; cls.OpenFolder(item, lvListView); cboPath.Text = cls.Path; Program.fmain.Text = item.Text; cls.HistoryAdd(); statusLabel1.Text = lvListView.Items.Count.ToString() + " object(s)";

}

Thực hiện việc xóa tệp tin, thư mục:

private void mnuDelete_Click(object sender, EventArgs e) { try { if (lvListView.Focused)//delete o listview { ListViewItem item = new ListViewItem(); item = lvListView.FocusedItem; clsitem.DeleteItem(item, lvListView); } else//delete o treeview { TreeNode dir = tvTreeView.SelectedNode; string pathDir = cboPath.Text.Trim(); if (!Microsoft.VisualBasic.FileIO.FileSystem.DirectoryExists(pathDir)) return; DialogResult d = MessageBox.Show("Bạn có chắc chắn muốn xoá thư mục '" +dir.Text + "' và tất cả nội dung bên trong?", "Xác nhận đã Xoá", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (d == DialogResult.Yes) { Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory(pathDir, Microsoft.VisualBasic.FileIO.DeleteDirectoryOption.DeleteAllContents); tvTreeView.Nodes.Remove(dir);

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 18

Page 19: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

} else return; } } catch { }

}

Thực hiện việc sao chép tệp tin, folder:

private void mnuCopy_Click(object sender, EventArgs e) { isCopy = true; try { //xem copy folder o listview hay la treeview if (lvListView.Focused)//copy o listview { item = lvListView.FocusedItem; if (item.SubItems[1].Text.Trim() == "File Folder")//copy folder { isDir = true; sourceDir = cboPath.Text.Trim() + item.Text; arrSrceDir = sourceDir.Split('\\'); folder = arrSrceDir[arrSrceDir.Length - 1]; clsitem.strSrceDir = sourceDir; } else//copy file { isDir = false; sourceFile = cboPath.Text.Trim() + item.Text; clsitem.strSrceFile = sourceFile; } } else //copy folder o treeview { isDir = true; sourceDir = cboPath.Text.Trim(); folder = tvTreeView.SelectedNode.Text; clsitem.strSrceDir = sourceDir; } cmnuPaste.Enabled = true; cmnutvPaste.Enabled = true; } catch (Exception ex) {

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 19

Page 20: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

MessageBox.Show("Không thể chép được. Có ngoại lệ sau" + " xảy ra:\n" + ex.Message, "Thất bại!"); }

}

Thực hiện việc dán tệp tin, folder:

private void mnuPaste_Click(object sender, EventArgs e) { try { strDestDir = Program.fmain.cboPath.Text.Trim(); strDest = strDestDir + folder; clsitem.strDestDir = strDestDir; if (isCopy == true)//copy/paste { if (Program.fmain.isDir) { Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(sourceDir, strDest); } else { string dest = strDestDir + item.Text.Trim(); Microsoft.VisualBasic.FileIO.FileSystem.CopyFile(sourceFile, dest); } } else //move/paste { if (Program.fmain.isDir) { Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(sourceDir, strDest); if (nodeCurrent != null) tvTreeView.Nodes.Remove(nodeCurrent); } else { string dest = strDestDir + item.Text.Trim(); Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(sourceFile, dest); } }

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 20

Page 21: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

} catch (Exception ex) { MessageBox.Show(ex.Message); } cls.OpenFolder(Program.fmain.cboPath.Text.Trim(), lvListView);

}

Thực hiện việc di chuyển file, folder:

private void mnuCut_Click(object sender, EventArgs e) { isCopy = false; try { //xem move folder o listview hay la treeview if (lvListView.Focused)//move o listview { item = lvListView.FocusedItem; foreach (ListViewItem lvi in lvListView.Items) { if (lvi.ForeColor == Color.Red) lvi.ForeColor = Color.Black; } item.ForeColor = Color.Red; if (item.SubItems[1].Text.Trim() == "File Folder")//move folder { isDir = true; sourceDir = cboPath.Text.Trim() + item.Text; arrSrceDir = sourceDir.Split('\\'); folder = arrSrceDir[arrSrceDir.Length - 1]; clsitem.strSrceDir = sourceDir; } else//move file { isDir = false; sourceFile = cboPath.Text.Trim() + item.Text; clsitem.strSrceFile = sourceFile; } } else //move folder o treeview { nodeCurrent = tvTreeView.SelectedNode; isDir = true; sourceDir = cboPath.Text.Trim(); folder = tvTreeView.SelectedNode.Text;

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 21

Page 22: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

clsitem.strSrceDir = sourceDir; } cmnuPaste.Enabled = true; cmnutvPaste.Enabled = true; } catch { }

}

Thực hiện việc sao chép và di chuyển đến trực tiếp:

private void mnuCopyTo_Click(object sender, EventArgs e) { string destDir; FolderBrowserDialog fb = new FolderBrowserDialog(); fb.Description = "Chọn đích cần copy đến :"; fb.ShowDialog(); try { if (lvListView.Focused)//copy o listview { item = lvListView.FocusedItem; if (item.SubItems[1].Text.Trim() == "File Folder") { isDir = true; sourceDir = cboPath.Text.Trim() + item.Text; arrSrceDir = sourceDir.Split('\\'); folder = arrSrceDir[arrSrceDir.Length - 1]; clsitem.strSrceDir = sourceDir; } else { isDir = false; sourceFile = cboPath.Text.Trim() + item.Text; folder = lvListView.FocusedItem.Text; clsitem.strSrceFile = sourceFile; } } else { isDir = true; sourceDir = cboPath.Text.Trim(); folder = tvTreeView.SelectedNode.Text; clsitem.strSrceDir = sourceDir; } destDir = fb.SelectedPath + "\\" + folder; if (destDir != "")

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 22

Page 23: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

{ if (isDir) Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(sourceDir, destDir); else Microsoft.VisualBasic.FileIO.FileSystem.CopyFile(sourceFile, destDir); } } catch(Exception ex) { MessageBox.Show(ex.Message); }

}

private void mnuMoveTo_Click(object sender, EventArgs e) { string destDir; FolderBrowserDialog fb = new FolderBrowserDialog(); fb.Description = "Chọn đích cần di chuyển đến :"; fb.ShowDialog(); try { if (lvListView.Focused)//move o listview { item = lvListView.FocusedItem; if (item.SubItems[1].Text.Trim() == "File Folder") { isDir = true; sourceDir = cboPath.Text.Trim() + item.Text; arrSrceDir = sourceDir.Split('\\'); folder = arrSrceDir[arrSrceDir.Length - 1]; clsitem.strSrceDir = sourceDir; } else { isDir = false; sourceFile = cboPath.Text.Trim() + item.Text; folder = lvListView.FocusedItem.Text; clsitem.strSrceFile = sourceFile; } } else //move o folder o treeview { isDir = true; sourceDir = cboPath.Text.Trim(); folder = tvTreeView.SelectedNode.Text;

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 23

Page 24: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

clsitem.strSrceDir = sourceDir; } destDir = fb.SelectedPath + "\\" + folder; if (destDir != "") { if (isDir) Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(sourceDir, destDir); else Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(sourceFile, destDir); if (lvListView.Focused) lvListView.Items.Remove(item); else tvTreeView.Nodes.Remove(tvTreeView.SelectedNode); } } catch (Exception ex) { MessageBox.Show(ex.Message); }

}

Thực hiện việc tạo các folder mới:

private void btnNewFolder_Click(object sender, EventArgs e) { string path = cboPath.Text.Trim() + "New Folder"; if (!Microsoft.VisualBasic.FileIO.FileSystem.DirectoryExists(path)) { Microsoft.VisualBasic.FileIO.FileSystem.CreateDirectory(path); } else { while (i > 0) { string path1 = cboPath.Text.Trim() + "New Folder(" + i.ToString() + ")"; if (!Microsoft.VisualBasic.FileIO.FileSystem.DirectoryExists(path1)) { Microsoft.VisualBasic.FileIO.FileSystem.CreateDirectory(path1); i = 2; break; }

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 24

Page 25: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

i++; } } cls.OpenFolder(cboPath.Text, lvListView); }

Thực hiện việc đổi tên File, Folder:

private void mnuRename_Click(object sender, EventArgs e) { if (lvListView.Focused) { lviCurrent = lvListView.FocusedItem; currentName = lviCurrent.Text; currentPath = cboPath.Text.Trim() + currentName; if (lviCurrent.SubItems[1].Text.Trim() == "File Folder")//rename folder { isDir = true; } else { isDir = false; } } else { isDir = true; nodeCurrent = tvTreeView.SelectedNode; currentName = nodeCurrent.Text; currentPath = cboPath.Text.Trim(); } Forms.frmRename frename = new frmRename(); frename.ShowDialog(); }

ở đoạn chương trình này thực hiện việc gọi Form con là frmRename để thực

hiện việc đổi tên.

private void btnOK_Click(object sender, EventArgs e) { try { if (Program.fmain.isDir)//rename thu muc { if (Microsoft.VisualBasic.FileIO.FileSystem.DirectoryExists(Program.fmain.currentPath)) {

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 25

Page 26: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

Microsoft.VisualBasic.FileIO.FileSystem.RenameDirectory(Program.fmain.currentPath, txtTenMoi.Text.Trim()); if (Program.fmain.nodeCurrent != null) Program.fmain.nodeCurrent.Text = txtTenMoi.Text; else Program.fmain.lviCurrent.Text = txtTenMoi.Text; this.Close(); } } else { if (Microsoft.VisualBasic.FileIO.FileSystem.FileExists(Program.fmain.currentPath)) { Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(Program.fmain.currentPath, txtTenMoi.Text.Trim()); Program.fmain.lviCurrent.Text = txtTenMoi.Text; this.Close(); } } } catch { } }

private void frmRename_Load(object sender, EventArgs e) { txtTenCu.Text = Program.fmain.currentName; txtTenMoi.Focus(); }

Thực hiện việc tìm kiếm các file, folder có trong hệ thống:

private void pnbtnSearch_Click(object sender, EventArgs e) { lvListView.Items.Clear(); try { int i = 0; if (lvListView.Columns.Count == 5) lvListView.Columns.RemoveAt(4); lvListView.Columns.Add("In Folder", 300, HorizontalAlignment.Left); DirectoryInfo searchDir = new DirectoryInfo(pathSearch);

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 26

Page 27: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

classSearch.searchDirectory(searchDir, txtFileName.Text); } catch { } if (lvListView.Items.Count == 0) { lvListView.Items.Add("Tìm Kiếm Hoàn Tất."); lvListView.Items.Add("Không có kết quả hiển thị."); } statusLabel1.Text = lvListView.Items.ToString() + "object(s)";

ở đây để thực hiện được việc tìm kiếm chi tiết các file, folder ta tạo lớp tìm kiếm classSearch để hiển thị các file, folder cần tìm kiếm.

class classSearch { public static int i = 0, j = 0; public static void searchDirectory(DirectoryInfo dir, string name) { if (dir.GetDirectories() != null) { foreach (DirectoryInfo di in dir.GetDirectories()) { if (di.Name.ToUpper().Contains(name.ToUpper().Trim())) { string[] subFolder = { di.Name, "File Folder", "", di.LastWriteTime.ToString(), di.FullName, di.Parent.FullName }; ListViewItem item = new ListViewItem(subFolder); item.ImageKey = "Folder"; Program.fmain.lvListView.Items.Add(item); } searchDirectory(di, name); } if (dir.GetFiles() != null) { foreach (FileInfo fi in dir.GetFiles()) { if (fi.Name.ToUpper().Contains(name.ToUpper().Trim())) { long size = fi.Length / 1024;

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 27

Page 28: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

string[] s = { fi.Name, fi.Extension.ToUpper(), size + " KB", fi.LastWriteTime.ToString(), fi.FullName }; ListViewItem item = new ListViewItem(s); item.ImageKey = "File"; Program.fmain.lvListView.Items.Add(item); } } } } } public static void SearchFile(DirectoryInfo dir, string fileName, string fileType) { if (dir.GetDirectories() != null) { foreach (DirectoryInfo di in dir.GetDirectories()) { SearchFile(di, fileName, fileType); } if (dir.GetFiles() != null) { foreach (FileInfo fi in dir.GetFiles()) { if (fi.Name.ToUpper().Contains(fileName.ToUpper().Trim()) && fileType.ToString().ToUpper().Contains(fi.Extension.ToUpper())) { long size = fi.Length / 1024; string[] s = { fi.Name, fi.Extension.ToUpper(), size + " KB", fi.LastWriteTime.ToString(), fi.FullName }; ListViewItem item = new ListViewItem(s); item.ImageKey = "File"; Program.fmain.lvListView.Items.Add(item); } } } } } public static void SearchFile(DirectoryInfo dir, string fileName, DateTime dateTime1,string fileType) { if (dir.GetDirectories() != null) {

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 28

Page 29: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

foreach (DirectoryInfo di in dir.GetDirectories()) { SearchFile(di, fileName,dateTime1,fileType); } if (dir.GetFiles() != null) { foreach (FileInfo fi in dir.GetFiles()) { if (fi.Name.ToUpper().Contains(fileName.ToUpper().Trim()) && fi.LastWriteTime > dateTime1 && fileType.ToString().ToUpper().Contains(fi.Extension.ToUpper())) { long size = fi.Length / 1024; string[] s = { fi.Name, fi.Extension.ToUpper(), size + " KB", fi.LastWriteTime.ToString(), fi.FullName }; ListViewItem item = new ListViewItem(s); item.ImageKey = "File"; Program.fmain.lvListView.Items.Add(item); } } } } } }

để thực hiện việc tìm kiếm hiệu quả hơn ta sử dụng đường dẫn để dễ dàng hơn trong việc tìm kiếm các file, folder.

private void chosearch_Click(object sender, EventArgs e) { FolderBrowserDialog fb = new FolderBrowserDialog(); fb.Description = "Bạn hãy chọn đường dẫn tìm kiếm: "; fb.ShowDialog(); pathSearch = fb.SelectedPath; if (pathSearch != "") { if (cboPath.Items.Count == 13) { cboPath.Items.RemoveAt(11); } if (cboPath.Items.Count < 13) { cboPath.Items.Add(pathSearch);

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 29

Page 30: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

} cboPath.SelectedItem = cboPath.Items[cboPath.Items.Count - 1]; } }

Thực hiện việc trở lại thư mục vừa vào của chương trình:

private void sbtnBack_ButtonClick_1(object sender, EventArgs e) { try { string path = cls.HistoryBack(lvListView, tvTreeView.Nodes[0]); string[] arr = path.Split('\\'); string name = arr[arr.Length - 1]; Program.fmain.Text = name; if (path != null) { cboPath.Text = path; statusLabel1.Text = lvListView.Items.Count.ToString() + " object(s)"; int Count = Back.Count; if (Count > 0) { TreeNode Node = new TreeNode(); Node = (TreeNode)Back[Count - 1]; Back.RemoveAt(Count - 1); sbtnBack.DropDown.Items.RemoveAt(Count - 1); Forward.Add(Node); History.InsertForward_DropdownButton(Node); } } } catch { } }

private void sbtnForward_ButtonClick_1(object sender, EventArgs e) { try { string path = cls.HistoryForward(lvListView, tvTreeView.Nodes[0]); string[] arr = path.Split('\\'); string name = arr[arr.Length - 1]; Program.fmain.Text = name; if (path != null)

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 30

Page 31: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

{ cboPath.Text = path; statusLabel1.Text = lvListView.Items.Count.ToString() + " object(s)"; } } catch { } }

Ngoài ra để chương trình hiển thị các ổ đĩa, folder đã truy xuất ta sử dụng lớp clsHistory để hiển thị các ổ đĩa, folder đã truy xuất.

class clsHistory { ArrayList history; int currentIndex; int size; public clsHistory() { history = new ArrayList(); history.Add(SpecialDirectories.Desktop + "\\"); currentIndex = 0; size = 50; } public void Add(string path) { if (path.Equals(history[history.Count - 1].ToString())) { return; } history.Add(path); if (history.Count > size) history.RemoveAt(0); currentIndex = history.Count-1; } public string Back() { if (currentIndex > 0) { currentIndex--; return history[currentIndex].ToString(); } return null; } public string BackItem(string item) { string path = ""; string[] items = new string[100]; if (history.Count == 0) return null;

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 31

Page 32: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

for (int i = 0; i < history.Count; i++) { string[] arr = history[i].ToString().Split('\\'); items[i] = arr[arr.Length - 1]; } for (int i = 0; i < items.Length; i++) { if (item == items[i]) path = history[i].ToString(); } return path; } public string Forward() { if (currentIndex < history.Count-1) { currentIndex++; return history[currentIndex].ToString(); } return null; } public string ForwardItem(string item) { string path = ""; if (currentIndex <history.Count-1) { string[] items = new string[100]; for (int i = 0; i < history.Count; i++) { string[] arr = history[i].ToString().Split('\\'); items[i] = arr[arr.Length - 1]; } for (int i = 0; i < items.Length; i++) { if (item == items[i]) path = history[i].ToString(); } } return path; } //Update toolstrip_Back_Dropdobuton public void InSertBack_DropDownbutton(TreeNode Node) { ToolStripMenuItem Items = new ToolStripMenuItem(); Items.Text = Node.Text; Items.Tag = Node.Tag; Program.fmain.sbtnBack.DropDownItems.Add(Items);

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 32

Page 33: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

} //Update cho toolstripForward_dropdownbutton public void InsertForward_DropdownButton(TreeNode Node) { ToolStripMenuItem items = new ToolStripMenuItem(); items.Text = Node.Text; items.Tag = Node.Tag; Program.fmain.sbtnForward.DropDownItems.Add(items); } }

Ngoài ra ta còn sử dụng các lớp clsTreeView để hiển thị các file, folder lên các cây thư mục Treeview và cây tệp tin Listview và clsItem để liệt kê các file, folder có trong Listview

Lớp clsTreeViewclass clsTreeView { private static string path = ""; public string Path { get { return path; } set { path = value; } } public static bool CreateTreeView(TreeView tv) { bool flag = false; try { //Desktop : root TreeNode desktop = new TreeNode(); desktop.Text = "Desktop"; desktop.Tag = "Desktop"; desktop.ImageKey = "Desktop"; desktop.SelectedImageKey = "Desktop"; DirectoryInfo DesktopFolder = new DirectoryInfo(SpecialDirectories.Desktop); foreach (DirectoryInfo di in DesktopFolder.GetDirectories()) { TreeNode folder = new TreeNode(di.Name); folder.SelectedImageKey = "Folder"; folder.ImageKey = "Folder";

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 33

Page 34: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

desktop.Nodes.Add(di.Name); } //My Documents : node[0] TreeNode MyDocuments = new TreeNode(); MyDocuments.Text = "My Documents"; MyDocuments.Tag = "Documents"; MyDocuments.ImageKey = "Document"; MyDocuments.SelectedImageKey = "Document"; MyDocuments.Nodes.Add(""); //My Computer : node[1] TreeNode MyComputer = new TreeNode(); MyComputer.Text = "My Computer"; MyComputer.Tag = "Computer"; MyComputer.ImageKey = "Computer"; MyComputer.SelectedImageKey = "Computer"; foreach (DriveInfo drvi in DriveInfo.GetDrives()) { TreeNode tnDrv = new TreeNode(); string imgKey = DriveTypeImageKey(drvi); tnDrv.SelectedImageKey = imgKey; tnDrv.ImageKey = imgKey; tnDrv.Text = drvi.Name; tnDrv.Nodes.Add(""); MyComputer.Nodes.Add(tnDrv); } desktop.Nodes.Insert(0, MyDocuments); desktop.Nodes.Insert(1, MyComputer); tv.Nodes.Add(desktop); flag = true; } catch(Exception ex) { flag = false; ShowError(ex); } return flag; } private static string DriveTypeImageKey(DriveInfo drvi) { string key = ""; switch (drvi.DriveType) { case DriveType.Fixed: { key = "HDD"; break; } case DriveType.CDRom: {

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 34

Page 35: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

key = "CD"; break; } case DriveType.Network: { key = "NET"; break; } case DriveType.Removable: { key = "RD"; break; } case DriveType.Unknown: { key = "Folder"; break; } default: { key = "HDD"; break; } } return key; } public static void ShowError(Exception ex) { MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } public void ShowErrorPath() { MessageBox.Show("Invalid path!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } public static TreeNode Expand(TreeNode parentNode) { try { DirectoryInfo rootDir = GetRootDir(parentNode); path = rootDir.FullName; parentNode.Nodes[0].Remove(); foreach (DirectoryInfo di in rootDir.GetDirectories()) { TreeNode tn = new TreeNode(); tn.Text = di.Name; tn.Nodes.Add(""); parentNode.Nodes.Add(tn);

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 35

Page 36: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

} } catch(Exception ex) { ShowError(ex); } return parentNode; } public static string GetPath(TreeNode parentNode) { if (parentNode.Text == "Desktop") return null; char[] arr ={ '\\' }; string path = ""; string[] nameList = parentNode.FullPath.Split(arr); string nodeName = nameList.GetValue(1).ToString(); switch (nodeName) { case "My Documents": path = SpecialDirectories.MyDocuments + "\\"; break; case "My Computer": path = "MyComputer"; break; default: path = ""; break; } if (path == "") path = SpecialDirectories.Desktop + "\\"; return path; } private static DirectoryInfo GetRootDir(TreeNode parentNode) { char[] arr ={ '\\' }; string path = ""; string[] nameList = parentNode.FullPath.Split(arr); string nodeName = nameList.GetValue(1).ToString(); switch (nodeName) { case "My Documents": path = SpecialDirectories.MyDocuments + "\\"; break; default: path = ""; break; } for (int i = 2; i < nameList.Length; i++)

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 36

Page 37: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

path += nameList[i] + "\\"; return new DirectoryInfo(path); } public void OpenFolder(ListViewItem lvItem, ListView listView) { try { string path = lvItem.SubItems[4].Text; if (path == "MyComputer") { GetAllDriver(listView); return; } FileInfo fi = new FileInfo(path); if (fi.Exists) { Process.Start(path); } else { DirectoryInfo rootDir = new DirectoryInfo(path + "\\"); if (!rootDir.Exists) { ShowErrorPath(); return; } GetAllInDirectory(rootDir, listView); } } catch (Exception ex) { ShowError(ex); } } public void OpenFolder(string path, ListView listView) { try { if (!path.EndsWith("\\")) path += "\\"; DirectoryInfo rootDir = new DirectoryInfo(path); if (!rootDir.Exists) { ShowErrorPath(); return; } GetAllInDirectory(rootDir, listView);

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 37

Page 38: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

} catch (Exception ex) { ShowError(ex); } } public void OpenFolder(TreeNode treeNode, ListView listView) { try { DirectoryInfo rootDir = null; if (treeNode.Text == "Desktop") { GetDesktop(treeNode, listView); return; }

if (treeNode.Parent.Text == "Desktop") { string nodeName = treeNode.Text; switch (nodeName) { case "My Computer": GetAllDriver(listView); break; case "My Documents": rootDir = GetRootDir(treeNode); GetAllInDirectory(rootDir, listView); break; default: rootDir = new DirectoryInfo(SpecialDirectories.Desktop); GetAllInDirectory(rootDir, listView); break; } } else { rootDir = GetRootDir(treeNode); GetAllInDirectory(rootDir, listView); } } catch (Exception ex) { ShowError(ex); } }

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 38

Page 39: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

public void ParentFolder(ListView listView, TreeView treeView) { try { //Desktop if (Path == "Desktop" || Path == "MyComputer") { GetDesktop(treeView.Nodes[0], listView); return; } DirectoryInfo rootDir = new DirectoryInfo(Path); if (!rootDir.Exists) { ShowErrorPath(); return; } if (rootDir.FullName.Equals(rootDir.Root.FullName)) { GetAllDriver(listView); } else { GetAllInDirectory(rootDir.Parent, listView); } } catch (Exception ex) { ShowError(ex); } } private void GetAllDriver(ListView listView) { try { ListViewItem item; listView.Items.Clear(); foreach (DriveInfo drv in DriveInfo.GetDrives()) { if (drv.IsReady) { item = CreatLVItem(drv); listView.Items.Add(item); } }

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 39

Page 40: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

this.Path = "MyComputer"; } catch (Exception ex) { ShowError(ex); } } private void GetAllInDirectory(DirectoryInfo rootDir, ListView listView) { try { ListViewItem item; listView.Items.Clear(); foreach (DirectoryInfo dir in rootDir.GetDirectories()) { item = CreatLVItem(dir); listView.Items.Add(item); } foreach (FileInfo file in rootDir.GetFiles()) { item = CreatLVItem(file); listView.Items.Add(item); } this.Path = rootDir.FullName; } catch (Exception ex) { ShowError(ex); } } private void GetDesktop(TreeNode treeNode, ListView listView) { try { ListViewItem item; listView.Items.Clear(); for (int i = 0; i < treeNode.Nodes.Count; i++) { item = CreatLVItem(treeNode.Nodes[i]); listView.Items.Add(item); } DirectoryInfo rootDir = new DirectoryInfo(SpecialDirectories.Desktop); foreach (FileInfo file in rootDir.GetFiles()) { item = CreatLVItem(file); listView.Items.Add(item);

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 40

Page 41: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

} this.Path = "Desktop"; } catch (Exception ex) { ShowError(ex); } } public static ListViewItem CreatLVItem(DirectoryInfo dir) { string[] s = { dir.Name, "File Folder", "", dir.LastWriteTime.ToString(), dir.FullName, dir.Parent.FullName }; ListViewItem item = new ListViewItem(s); item.ImageKey = "Folder"; return item; } public static ListViewItem CreatLVItem(FileInfo file) { long size = file.Length / 1024; string[] s = { file.Name, file.Extension.ToUpper(), size + " KB", file.LastWriteTime.ToString(), file.FullName, file.Directory.FullName }; ListViewItem item = new ListViewItem(s); //item.ImageKey = "File"; switch (file.Extension.ToUpper()) { case ".TXT": case ".DIZ": case ".LOG": item.ImageKey = "txt"; break; case ".PDF": item.ImageKey = "pdf"; break; case ".HTM": case "HTML.": item.ImageKey = "htm"; break; case ".DOC": item.ImageKey = "doc"; break; case ".EXE": item.ImageKey = "exe"; break; case ".JPG": case ".BMP": item.ImageKey = "bmp";

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 41

Page 42: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

break; case ".SLN": item.ImageKey = "sln"; break; case ".MP3": case ".WAV": case ".WMV": case ".ASF": case ".MPEG": case ".AVI": case ".DAT": item.ImageKey = "music"; break; case ".RAR": case ".ZIP": case ".DLL": case ".REG": item.ImageKey = "rar"; break; case".INI": case ".INF": item.ImageKey = "inf"; break; case ".SWF": case ".FLV": case ".FLA": item.ImageKey = "swf"; break; default: item.ImageKey = "File"; break; } return item; } public static ListViewItem CreatLVItem(DriveInfo drv) { string name = ""; string driveType = ""; string size = ""; string free = "";

if (drv.DriveType != DriveType.CDRom && drv.DriveType != DriveType.Removable) { double t = Math.Round((double)drv.TotalSize / (1024 * 1024 * 1024), 2); double f = Math.Round((double)drv.AvailableFreeSpace / (1024 * 1024 * 1024), 2);

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 42

Page 43: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

size = t + " GB"; free = f + " GB";

if (drv.VolumeLabel != null) name = drv.VolumeLabel + " " + drv.Name; } else { name = drv.Name; } driveType = drv.DriveType.ToString(); string[] s = { name, driveType, size, free, drv.Name, "" }; ListViewItem item = new ListViewItem(s); item.ImageKey = DriveTypeImageKey(drv); return item; } private static ListViewItem CreatLVItem(TreeNode treeNode) { ListViewItem item = null; if (treeNode.Parent.Text == "Desktop") { string path = GetPath(treeNode); string[] s = { treeNode.Text, "", "", "", path, "Desktop" }; item = new ListViewItem(s); if (treeNode.ImageKey.Trim() != string.Empty) item.ImageKey = treeNode.ImageKey; else item.ImageKey = "Default"; } return item; } #region History clsHistory history = new clsHistory(); public void HistoryAdd() { history.Add(this.Path); } public string HistoryBack(ListView listView, TreeNode treeNode) { return OpenHistory(history.Back(), listView, treeNode); } public string HistoryForward(ListView listView, TreeNode treeNode) {

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 43

Page 44: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

return OpenHistory(history.Forward(), listView, treeNode); } public string OpenHistory(string path, ListView listView, TreeNode treeNode) { switch (path) { case null: break; case "Desktop": GetDesktop(treeNode, listView); break; case "MyComputer": GetAllDriver(listView); break; default: OpenFolder(path, listView); break; } return path; } #endregion }

Lớp clsItem

class clsItem { clsTreeView cls = new clsTreeView(); private static string sourceDir = "", dest = "", sourceFile = ""; public string strSrceFile { set { sourceFile = value; } get { return sourceFile; } } public string strSrceDir { set { sourceDir = value; } get {

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 44

Page 45: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

return sourceDir; } } public string strDestDir { set { dest = value; } get { return dest; } } public void DeleteItem(ListViewItem item, ListView listView) { try { string path = item.SubItems[4].Text; if (item.SubItems[1].Text == "File Folder") { DirectoryInfo dir = new DirectoryInfo(path); if (!dir.Exists) { cls.ShowErrorPath(); return; } else { DialogResult d = MessageBox.Show("Bạn có chắc chắn muốn xoá thư mục '" + item.Text.ToString() + "' và tất cả\n nội dung bên trong?", "Xác Nhận Đã Xoá", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (d == DialogResult.Yes) { dir.Delete(true); } else return; } } else { FileInfo file = new FileInfo(path); if (!file.Exists) { cls.ShowErrorPath();

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 45

Page 46: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

return; } else { DialogResult dd = MessageBox.Show("Bạn có chắc chắn muốn xoá File '" + item.Text.ToString() + "'?", "Xác Nhận Đã Xoá", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (dd == DialogResult.Yes) { file.Delete(); } else return; } } cls.OpenFolder(cls.Path, listView);

} catch (Exception ex) { clsTreeView.ShowError(ex); } } public void MoveItem(string pathMove, ListViewItem item, ListView listView) { try { string path = item.SubItems[4].Text; if (item.SubItems[1].Text == "File Folder") { DirectoryInfo dir = new DirectoryInfo(path); if (!dir.Exists) { cls.ShowErrorPath(); return; } dir.MoveTo(pathMove); } else { FileInfo file = new FileInfo(path); if (!file.Exists) { cls.ShowErrorPath(); return; } file.MoveTo(pathMove);

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 46

Page 47: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

} cls.OpenFolder(cls.Path, listView); } catch (Exception ex) { clsTreeView.ShowError(ex); } } //Ham liet dem tat ca so files va folders co trong mot thu muc public static int folderCount = 0, fileCount = 0; public static long folderSize = 0; public static void Contains(DirectoryInfo dir) { foreach (DirectoryInfo di in dir.GetDirectories()) { folderCount++; Contains(di); } foreach (FileInfo fi in dir.GetFiles()) { fileCount++; folderSize += fi.Length; } } }

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 47

Page 48: Chương Trình Quản Lý File Trên Hệ Điều Hành

Chương trình quản lý file trên hệ điều hành

SVTH : Phạm Văn Thắng – Phạm Đức Linh – Lớp 07CLC2 Trang 48