Directory last accessed: 2003-05-26 2:25:25 PMDirectory attribute list: Directory Directory contains: 147 files Bạn có thể sử dụng các phương thức tĩnh của lớp File và Directory thay c
Trang 1using System;
using System.IO;
public class FileInformation {
private static void Main(string[] args) {
if (args.Length == 0) {
Console.WriteLine("Please supply a file name:”);
return;
}
FileInfo file = new FileInfo(args[0]);
// Hiển thị thông tin file
Console.WriteLine("Checking file: " + file.Name);
Console.WriteLine("File exists: " + file.Exists.ToString());
if (file.Exists) {
Console.Write("File created: ");
Console.WriteLine(file.CreationTime.ToString());
Console.Write("File last updated: ");
Console.WriteLine(file.LastWriteTime.ToString());
Console.Write("File last accessed: ");
Console.WriteLine(file.LastAccessTime.ToString());
Console.Write("File size (bytes): ");
Console.WriteLine(file.Length.ToString());
Console.Write("File attribute list: ");
Console.WriteLine(file.Attributes.ToString());
}
Console.WriteLine();
// Hiển thị thông tin thư mục
DirectoryInfo dir = file.Directory;
Trang 2
Console.WriteLine("Checking directory: " + dir.Name);
Console.WriteLine("In directory: " + dir.Parent.Name);
Console.Write("Directory exists: ");
Console.WriteLine(dir.Exists.ToString());
if (dir.Exists) {
Console.Write("Directory created: ");
Console.WriteLine(dir.CreationTime.ToString());
Console.Write("Directory last updated: ");
Console.WriteLine(dir.LastWriteTime.ToString());
Console.Write("Directory last accessed: ");
Console.WriteLine(dir.LastAccessTime.ToString());
Console.Write("Directory attribute list: ");
Console.WriteLine(dir.Attributes.ToString());
Console.WriteLine("Directory contains: " +
dir.GetFiles().Length.ToString() + " files");
}
Console.ReadLine();
}
}
Nếu bạn thực thi lệnh FileInformation c:\windows\win.ini, kết xuất có thể như sau: Checking file: win.ini
File exists: True
File created: 2001-08-23 8:00:00 AM
File last updated: 2003-03-22 9:55:16 AM
File last accessed: 2003-05-26 2:21:53 PM
File size (bytes): 2128
File attribute list: Archive
Checking directory: windows
In directory: c:\
Directory exists: True
Directory created: 2000-01-01 8:03:33 AM
Trang 3Directory last accessed: 2003-05-26 2:25:25 PM
Directory attribute list: Directory
Directory contains: 147 files
Bạn có thể sử dụng các phương thức tĩnh của lớp File và Directory thay cho các
phương thức của lớp FileInfo và DirectoryInfo, nhưng bạn phải truyền tên file hay đường dẫn mỗi lần gọi Trong trường hợp thực hiện nhiều thao tác với cùng một file hay thư mục thì sử dụng các lớp FileInfo và DirectoryInfo nhanh hơn,
vì chúng thực hiện kiểm tra bảo mật chỉ một lần.
2. Thi t l p các thu c tính c a file và th m c Thi t l p các thu c tính c a file và th m c ế ậ ế ậ ộ ộ ủ ủ ư ụ ư ụ
Bạn cần kiểm tra hay thay đổi các thuộc tính của file hay thư mục.
Tạo đối tượng System.IO.FileInfo cho file hay tạo đối tượng
System.IO.DirectoryInfo cho thư mục Sau đó, sử dụng các toán tử AND (&) và
OR (| ) để thay đổi giá trị của thuộc tính Attributes.
Các thuộc tính FileInfo.Attributes và DirectoryInfo.Attributes mô tả các thuộc tính của
file như archive, system, hidden, read-only, compressed, và encrypted (tham khảo thêm trong tài liệu MSDN) Vì một file có thể có nhiều thuộc tính nên Attributes là một tập các giá trị
kiểu liệt kê Để kiểm tra hay thay đổi một thuộc tính đơn lẻ, bạn cần sử dụng các phép toán trên bit.
Ví dụ sau nhận vào một file và kiểm tra thuộc tính read-only:
using System;
using System.IO;
public class Attributes {
private static void Main() {
// Giả sử file này có thuộc tính archive và read-only
FileInfo file = new FileInfo("data.txt");
// Lệnh này sẽ hiển thị chuỗi "ReadOnly, Archive"
Console.WriteLine(file.Attributes.ToString());
// Điều kiện dưới đây sai, vì còn có thuộc tính khác
// đã được thiết lập
if (file.Attributes == FileAttributes.ReadOnly) {
Console.WriteLine("File is read-only (faulty test).");
Trang 4}
// Điều kiện dưới đây đúng, vì nó chỉ lọc ra
// thuộc tính read-only
if ((file.Attributes & FileAttributes.ReadOnly) ==
FileAttributes.ReadOnly) {
Console.WriteLine("File is read-only (correct test).");
}
Console.ReadLine();
}
}
Để hiểu được ví dụ trên, bạn cần biết rằng Attributes được tạo thành (ở dạng
nhị phân) bởi một dãy các chữ số 0 và 1, chẳng hạn 00010011 Mỗi chữ số 1 cho biết một thuộc tính được thiết lập, mỗi chữ số 0 cho biết một thuộc tính không được thiết lập Khi bạn sử dụng phép AND, nó sẽ so sánh mỗi chữ số này với mỗi chữ số tương ứng trong giá trị liệt kê Ví dụ, nếu bạn AND giá trị 00100001 (mô
tả thuộc tính archive và read-only) với giá trị liệt kê 00000001 (mô tả thuộc tính
read-only), kết quả sẽ là 00000001 (chỉ có được chữ số 1 khi ở cả hai vị trí tương
ứng đều là 1).
Khi thiết lập một thuộc tính, bạn cũng phải sử dụng phép toán trên bit Trong trường hợp này, bạn cần cẩn thận để không vô ý xóa các thuộc tính khác.
// Chỉ thêm thuộc tính read-ony
file.Attributes = file.Attributes | FileAttributes.ReadOnly;
// Chỉ xóa thuộc tính read-only
file.Attributes = file.Attributes & ~FileAttributes.ReadOnly;
3. Chép, chuy n, xóa file hay th m c Chép, chuy n, xóa file hay th m c ể ể ư ụ ư ụ
Bạn cần chép, chuyển, xóa một file hay thư mục
Tạo đối tượng System.IO.FileInfo cho file hay đối tượng
System.IO.DirectoryInfo cho thư mục, truyền đường dẫn cho phương thức khởi dựng Sử dụng các phương thức của đối tượng để chép, chuyển, xóa.
Các lớp FileInfo và DirectoryInfo cung cấp nhiều phương thức dùng để thao tác trên file và thư mục Bảng 9.2 và 9.3 trình bày các phương thức của lớp FileInfo và DirectoryInfo.
Bảng 9.2 Các phương thức dùng để thao tác đối tượng FileInfo
Trang 5Chép một file sang đường dẫn mới, tên file được chỉ định trong đối số Nó cũng trả về một đối tượng FileInfo mô tả file mới được chép Bạn có thể truyền thêm một thông số tùy chọn
có giá trị true để cho phép chép đè.
Create và CreateText
Create tạo file được chỉ định và trả về một đối tượng FileStream dùng để ghi ra file CreateText cũng thực hiện như thế, nhưng trả về đối tượng StreamWriter gói lấy stream Xem mục 9.7 và 9.8 để có thêm thông tin về việc ghi file.
Open, OpenRead, OpenText,
và OpenWrite
Mở một file (nếu nó tồn tại) OpenRead và OpenText mở file trong chế độ chỉ-đọc, trả về một đối tượng FileStream hay StreamReader OpenWrite mở file trong chế độ chỉ-ghi, trả về một đối tượng FileStream Xem thêm mục 9.7 và 9.8 để có thêm thông tin về việc đọc file.
Delete Xóa file (nếu nó tồn tại)
MoveTo
Chuyển một file đến đường dẫn mới, tên file được chỉ định trong đối số MoveTo cũng được sử dụng để đổi tên một file mà không chuyển chỗ.
Bảng 9.3 Các phương thức dùng để thao tác đối tượng DirectoryInfo
Create Tạo thư mục được chỉ định Nếu đường dẫn chỉ định nhiều thư
mục chưa tồn tại, tất cả sẽ được tạo một lượt.
CreateSubdirectory
Tạo một thư mục với tên cụ thể bên trong thư mục được mô tả bởi đối tượng DirectoryInfo Nó cũng trả về một đối tượng DirectoryInfo mô tả thư mục con
Delete
Xóa một thư mục (nếu nó tồn tại) Nếu muốn xóa một thư mục
có chứa các thư mục khác, bạn phải sử dụng phương thức nạp chồng Delete chấp nhận một thông số có tên là recursive và thiết lập nó là true.
MoveTo Chuyển một thư mục đến đường dẫn mới MoveTo có thể được
sử dụng để đổi tên một thư mục mà không chuyển chỗ.
Lớp DirectoryInfo không có phương thức nào dùng để sao chép thư mục Tuy nhiên, bạn có thể dễ dàng viết được một phương thức như thế dựa trên kỹ thuật đệ quy và phương thức CopyTo của đối tượng FileInfo:
using System;
using System.IO;
public class FileSystemUtil {
Trang 6public static void CopyDirectory(DirectoryInfo source,
DirectoryInfo destination) {
if (!destination.Exists) {
destination.Create();
}
// Chép tất cả file
FileInfo[] files = source.GetFiles();
foreach (FileInfo file in files) {
file.CopyTo(Path.Combine(destination.FullName, file.Name));
}
// Xử lý các thư mục con
DirectoryInfo[] dirs = sourceDir.GetDirectories();
foreach (DirectoryInfo dir in dirs) {
// Lấy thư mục đích
string destinationDir = Path.Combine(destination.FullName,
dir.Name);
// Gọi đệ quy CopyDirectory()
CopyDirectory(dir, new DirectoryInfo(destinationDir));
}
}
}
Ví dụ sau sử dụng phương thức vừa viết ở trên để chép thư mục, đường dẫn các thư mục được truyền qua dòng lệnh:
public class CopyDir {
private static void Main(string[] args) {
if (args.Length != 2) {
Trang 7"CopyDir [sourcePath] [destinationPath]");
return;
}
DirectoryInfo sourceDir = new DirectoryInfo(args[0]);
DirectoryInfo destinationDir = new DirectoryInfo(args[1]);
FileSystemUtil.CopyDirectory(new DirectoryInfo(sourceDir),
new DirectoryInfo(destinationDir));
Console.WriteLine("Copy complete.");
Console.ReadLine();
}
}
4. Tính kích th Tính kích th ướ ủ ướ ủ c c a th m c c c a th m c ư ụ ư ụ
Bạn cần tính kích thước của tất cả file nằm trong một thư mục (hoặc cả trong
các thư mục con của nó).
Duyệt qua tất cả file trong thư mục, tính tổng các thuộc tính FileInfo.Length của
chúng Sử dụng kỹ thuật đệ quy để tính cho cả các file nằm trong các thư mục con.
Lớp DirectoryInfo không có thuộc tính nào trả về thông tin kích thước Tuy nhiên, bạn có thể
dễ dàng tính được kích thước của tất cả các file nằm trong một thư mục bằng thuộc tính FileInfo.Length
Phương thức dưới đây sử dụng kỹ thuật trên và có thể tùy chọn duyệt đệ quy qua các thư mục con:
using System;
using System.IO;
public class FileSystemUtil {
public static long CalculateDirectorySize(DirectoryInfo directory,
bool includeSubdirectories) {
long totalSize = 0;
// Duyệt tất cả các file trong thư mục
Trang 8FileInfo[] files = directory.GetFiles();
foreach (FileInfo file in files) {
totalSize += file.Length;
}
// Duyệt tất cả các thư mục con
if (includeSubdirectories) {
DirectoryInfo[] dirs = directory.GetDirectories();
foreach (DirectoryInfo dir in dirs) {
totalSize += CalculateDirectorySize(dir, true);
}
}
return totalSize;
}
}
Và dưới đây là ứng dụng thử nghiệm phương thức trên:
using System;
using System.IO;
public class CalculateDirSize {
private static void Main(string[] args) {
if (args.Length == 0) {
Console.WriteLine("Please supply a directory path."); return;
}
DirectoryInfo dir = new DirectoryInfo(args[0]);
Console.WriteLine("Total size: " +
FileSystemUtil.CalculateDirectorySize(dir, true).ToString() + " bytes.");
Console.ReadLine();
Trang 95. Truy xu t thông tin phiên b n c a file Truy xu t thông tin phiên b n c a file ấ ấ ả ủ ả ủ
Bạn cần truy xuất các thông tin về phiên bản của file như publisher, revision
number, comment…
Sử dụng phương thức tĩnh GetVersionInfo của lớp System.Diagnostics
FileVersionInfo.
.NET Framework cho phép bạn truy xuất các thông tin về file mà không cần dựa vào Windows API Bạn chỉ cần sử dụng lớp FileVersionInfo và gọi phương thức GetVersionInfo với đối số là tên file Kế đó, bạn có thể truy xuất thông tin thông qua các thuộc tính của FileVersionInfo
using System;
using System.Diagnostics;
public class VersionInfo {
private static void Main(string[] args) {
if (args.Length == 0) {
Console.WriteLine("Please supply a file name.");
return;
}
FileVersionInfo info = FileVersionInfo.GetVersionInfo(args[0]);
// Hiển thị các thông tin về phiên bản
Console.WriteLine("Checking File: " + info.FileName);
Console.WriteLine("Product Name: " + info.ProductName);
Console.WriteLine("Product Version: " + info.ProductVersion);
Console.WriteLine("Company Name: " + info.CompanyName);
Console.WriteLine("File Version: " + info.FileVersion);
Console.WriteLine("File Description: " + info.FileDescription);
Console.WriteLine("Original Filename: " + info.OriginalFilename);
Console.WriteLine("Legal Copyright: " + info.LegalCopyright);
Console.WriteLine("InternalName: " + info.InternalName);
Console.WriteLine("IsDebug: " + info.IsDebug);
Trang 10Console.WriteLine("IsPatched: " + info.IsPatched);
Console.WriteLine("IsPreRelease: " + info.IsPreRelease);
Console.WriteLine("IsPrivateBuild: " + info.IsPrivateBuild);
Console.WriteLine("IsSpecialBuild: " + info.IsSpecialBuild);
Console.ReadLine();
}
}
Dưới đây là kết xuất khi bạn chạy lệnh VersionInfo c:\windows\explorer.exe:
Checking File: c:\windows\explorer.exe
Product Name: Microsoft® Windows® Operating System
Product Version: 6.00.2600.0000
Company Name: Microsoft Corporation
File Version: 6.00.2600.0000 (xpclient.010817-1148)
File Description: Windows Explorer
Original Filename: EXPLORER.EXE
Legal Copyright: © Microsoft Corporation All rights reserved
InternalName: explorer
IsDebug: False
IsPatched: False
IsPreRelease: False
IsPrivateBuild: False
IsSpecialBuild: False®
6. S d ng TreeView đ hi n th cây th m c just-in-time S d ng TreeView đ hi n th cây th m c just-in-time ử ụ ử ụ ể ể ể ể ị ị ư ụ ư ụ
Bạn cần hiển thị một cây thư mục trong TreeView Tuy nhiên, việc lấp đầy cấu
trúc cây thư mục khi khởi động tốn quá nhiều thời gian.
Thêm cấp thư mục đầu tiên vào TreeView, và thêm một nút giả (ẩn) vào mỗi
nhánh Phản ứng lại sự kiện TreeView.BeforeExpand để thêm các thư mục con vào một nhánh trước khi nó được hiển thị.
Bạn có thể sử dụng kỹ thuật đệ quy để xây dựng toàn bộ cây thư mục Tuy nhiên, việc quét hệ thống file theo cách này có thể chậm, đặc biệt đối với các ổ đĩa lớn Vì lý do này, các phần
mềm quản lý file chuyên nghiệp (bao gồm Windows Explorer) sử dụng một kỹ thuật khác: chỉ
hiển thị những thông tin nào người dùng cần đến.