Bài giảng Ngôn ngữ C#
Khoảng 80 từ khóa
• Hỗ trợ lập trình cấu trúc, lập trình hướng đối tượng, hướng
thành phần (Component oriented)
• Có từ khóa khai báo dành cho thuộc tính (property)
• Cho phép tạo sưu liệu trực tiếp bên trong mã nguồn (dùng
tool mã nguồn mở NDoc phát sinh ra sưu liệu)
• Hỗ trợ khái niệm interface (tương tự java)
• Cơ chế tự động dọn rác (tương tự java)
• Truyền tham số kiểu: in(ø), out, ref
một thành phần có trong
hashtable.
ContainsKey() Xác định xem hashtable có chứa một khóa xác
định
CopyTo() Sao chép những thành phần của hashtable
đến
mảng một chiều đã tồn tại
GetEnumerator() Trả về một enumerator cho hashtable.
Remove() Xóa một thành phần với khóa xác định.
Hashtables
Hashtables
01 using System;
02 using System.Collections;
03 public class Tester
04 {
05 static void Main()
06 {
07 // tạo và khởi tạo hashtable
08 Hashtable hashTable = new Hashtable();
09 hashTable.Add("00440123","Ngoc Thao");
10 hashTable.Add("00123001","My Tien");
11 hashTable.Add("00330124","Thanh Tung");
12 // truy cập qua thuộc tính Item
13 Console.WriteLine("myHashtable[\"00440123\"]: {0}",
hashTable["00440123"]);
14 }
15 }
16
• Thư viện System.IO cung cấp nhiều lớp dùng cho việc đọc, ghi
file cũng như việc thao tác với file và thư mục
• Một số lớp chính của System.IO
System.IO
DriveInfo
Thuộc tính/
Phương thức cơ
bản
Mô tả
DriveFormat Tên của file system, ví dụ: NTFS/ FAT32
DriveType Cho biết lọai ổ đĩa. Kiểu dữ liệu trả về là
DriveType: CDRom, Fixed, Network, Ram,
Removable, Unknown
IsReady Cho biết ổ đĩa đã sẵn sàng Read/Write.
Name Tên ổ đĩa
TotalFreeSpace Xem dung lượng đĩa trống
TotalSize Xem tổng dung lượng đĩa
GetDrives() Lấy danh sách ổ đĩa hiện có
01 using System;
02 using System.IO;
03 class Test
04 {
05 public static void Main()
06 {
07 DriveInfo[] allDrives = DriveInfo.GetDrives();
08 foreach (DriveInfo d in allDrives)
09 {
10 Console.WriteLine("Drive {0}", d.Name);
11 Console.WriteLine(" File type: {0}", d.DriveType);
12 if (d.IsReady == true)
13 {
14 Console.WriteLine(" Volume label: {0}",
d.VolumeLabel);
15 Console.WriteLine(" File system: {0}",
d.DriveFormat);
16 Console.WriteLine(
17 " Available space to current user:{0, 15}
bytes",
18 d.AvailableFreeSpace);
DriveInfo
19 Console.WriteLine(
20 " Total available space: {0, 15} bytes",
21 d.TotalFreeSpace);
22 Console.WriteLine(
23 " Total size of drive: {0, 15} bytes",
24 d.TotalSize);
25 }
26 }
27 }
28 }
DriveInfo
Thuộc tính/ phương thức
cơ bản
Mô tả
CreationTime Xem hoặc thiết lập thời gian tạo thư mục
Exists Kiểm tra thư mục tồn tại trên ổ đĩa
FullName Lấy đường dẫn của tới thư mục
LastAccessTime Cho biết thời gian cuối cùng thư mục (file) được truy cập
Name Cho biết tên của thư mục
Parent Trả về thư mục cha.
FileAttributes Attributes Cho biết thuộc tính của thự mục (file) FileAttributes là 1
enum gồm các giá trị như: Directory, Readonly, Hidden,…
Create() Tạo thư mục
Delete() Xóa thư mục
MoveTo() Di chuyển thư mục
GetDirectories() Lấy các thư mục con trong thư mục
GetFiles Lấy tất cả các tập tin trong thư mục
DirectoryInfo
01 using System;
02 using System.IO;
03 class Test
04 {
05 public static void Main()
06 {
07 // Specify the directories you want to manipulate.
08 DirectoryInfo di = new DirectoryInfo(@"c:\MyDir");
09 try
10 {
11 // Determine whether the directory exists.
12 if (di.Exists)
13 {
14 // Indicate that the directory already exists.
15 Console.WriteLine("That path exists already.");
16 return;
17 }
18 // Try to create the directory.
19 di.Create();
20 Console.WriteLine("The directory was created
successfully.");
DirectoryInfo
21 // Delete the directory.
22 di.Delete();
23 Console.WriteLine("The directory was deleted
successfully.");
24 }
25 catch (Exception e)
26 {
27 Console.WriteLine("The process failed: {0}",
e.ToString());
28 }
29 finally { }
30 }
31 }
DirectoryInfo
FileInfo
Thuộc tính/Phương
thức cơ bản
Mô tả
CreationTime Xem hoặc thiết lập thời gian tạo thư mục
Exists Kiểm tra thư mục tồn tại trên ổ đĩa
Directory Trả về đối tượng thư mục cha
DirectoryName Trả về chuỗi đường dẫn (full path) của thư mục cha
Extension Trả về tên đuôi file (txt,bat,exe,…)
Name Cho biết tên của file
Attributes Cho biết thuộc tính của file
CopyTo() Copy file đến 1 nơi khác
Create() Tạo file
Delete() Xóa file
MoveTo() Di chuyển file hoặc đổi tên file
CreateText Tạo StreamWriter để ghi file
OpenText Tạo StreamReader để đọc file
ReplaceFile Thay đổi nội dung file
01 using System;
02 using System.IO;
03 class Test
04 {
05 public static void Main()
06 {
07 string path = Path.GetTempFileName();
08 FileInfo fi1 = new FileInfo(path);
09 //Create a file to write to.
10 using (StreamWriter sw = fi1.CreateText())
11 {
12 sw.WriteLine("Hello");
13 sw.WriteLine("And");
14 sw.WriteLine("Welcome");
15 }
16 //Open the file to read from.
17 using (StreamReader sr = fi1.OpenText())
18 {
19 string s = "";
20 while ((s = sr.ReadLine()) != null)
21 {
22 Console.WriteLine(s);
23 }
24 }
FileInfo
25 try
26 {
27 string path2 = Path.GetTempFileName();
28 FileInfo fi2 = new FileInfo(path2);
29 //Ensure that the target does not exist.
30 fi2.Delete();
31 //Copy the file.
32 fi1.CopyTo(path2);
33 Console.WriteLine("{0} was copied to {1}.", path,
path2);
34 //Delete the newly created file.
35 fi2.Delete();
36 Console.WriteLine("{0} was successfully deleted.",
path2);
37 }
38 catch (Exception e)
39 {
40 Console.WriteLine("The process failed: {0}",
e.ToString());
41 }
42 }
43 }
FileInfo
• Đọc và viết dữ liệu sẽ được thực hiện thông qua
lớp Stream.
• Stream là 1 luồng dữ liệu, nó đưa dữ liệu từ
điểm bắt đầu đến điểm cuối.
• System.IO.Stream là một lớp abstract định
nghĩa một số thành viên có khả năng hỗ trợ việc
đọc/viết đồng bộ (synchronus) hoặc không đồng
bộ (asynchronous) đối với khối trữ tin
Xử lí đọc/ghi file
Thuộc tính/Phương
thức cơ bản
Mô tả
CanRead Luồng có hỗ trợ đọc
CanSeek Luồn có hỗ trợ di chuyển con trỏ
CanTimeOut Xác định xem luồng có timeout hay không
CanWrite Luồng có hỗ trợ ghi
Length Chiều dài (theo bytes) của luồng
ReadTimeout Thiết lập timeout cho phương thức Read
WriteTimeout Thiết lập timeout cho phương thức Write
Position Lấy hoặc xác lập vị trí con trỏ trong luồng
Close() Đóng luồng và giải phóng tài nguôn
Flush() Đẩy toàn bộ dữ liệu buffer trong luồng lên trên thiết bị
Read() Thực thi phương thức đọc mảng byte trên luồng.
Seek() Di chuyển vị trí con trỏ đọc
Write() Ghi mảng byte lên trên luồng
Stream Class
FileStream Class
Lớp FileStream là lớp dẫn xuất từ lớp Stream. FileStream có một
số phương thức và thuộc tính riêng.
Thuộc tính/Phương
thức cơ bản
Mô tả
Name Lấy tên của file
Lock() Khóa file, tránh truy xuất đồng thời lên File
Unlock Mở khóa file, có thể truy xuất
đồng thời lên file
StreamReader
Thuộc Tính Mô tả
BaseStream Trả về luồng đọc
CurrentEncoding Lấy thông tin định dạng của luồng đang sử dụng
EndOfStream Xác định con trỏ đọc đến cuối luồng chưa
Phương thức Mô tả
Close Đóng luồng và giải phóng tài nguyên
Peek Trả về giá trị kí tự tiếp theo trong luồng, không di
chuyễn con trỏ đọc.
Read Thực thi phương thức đọc mảng các kí tự trên luồng.
ReadBlock Đọc khối kí tự tiếp theo trên luồng.
ReadLine Đọc nguyên dòng trên luồng
ReadToEnd Đọc tất cả các kí tự tới cuối luồng
StreamReader có thể dùng để đọc văn bản
01 using System;
02 using System.IO;
03 class Test
04 {
05 public static void Main()
06 {
07 try
08 {
09 // Tạo một StreamReader để đọc file
10 using (StreamReader sr = new StreamReader("TestFile.txt"))
11 {
12 string line;
13 // Đọc từng dòng của File
14 while ((line = sr.ReadLine()) != null)
15 {
16 Console.WriteLine(line);
17 }
18 }
19 }
20 catch (Exception e)
21 {
22 // Hiển thị thông điệp lỗi
23 Console.WriteLine("The file could not be read:");
24 Console.WriteLine(e.Message);
25 }
26 }
27 }
Ví dụ
Thuộc tính Mô tả
AutoFlush Thiết lập cơ chế tự động Flush, sau mỗi lệnh Write
BaseStream Trả về luồng bên dưới
Encoding Lấy chế độ mã hóa hiện hành của luồng
StreamWriter
Phương thức Mô tả
Close Đóng luồng và giải phóng tài nguyên
Write Ghi vào luồng
WriteLine Ghi một chuỗi kí tự vào luồng và xuống hàng
StreamWriter có thể dùng để ghi văn bản
01 using System;
02 using System.IO;
03 class Program
04 {
05 static void Main(string[] args)
06 {
07 // Lấy các thư mục hiện hành trên ổ đĩa
08 DirectoryInfo[] cDirs = new
DirectoryInfo(@"c:\").GetDirectories();
09 // Viết tên các thư mục vào file
10 using (StreamWriter sw = new
StreamWriter("CDriveDirs.txt"))
11 {
12 foreach (DirectoryInfo dir in cDirs)
13 {
14 sw.WriteLine(dir.Name);
15
16 }
17 }
Ví dụ
18 // Đọc và hiển thi tên thư mục từ file
19 string line = "";
20 using (StreamReader sr = new
StreamReader("CDriveDirs.txt"))
21 {
22 while ((line = sr.ReadLine()) != null)
23 {
24 Console.WriteLine(line);
25 }
26 }
27 }
28 }
29
Ví dụ
Ví dụ
Tương tự như StreamReader và StreamWriter, BinaryReader và
BinaryWriter có thể dùng dể đọc file nhị phân
FileStream theFile =
File.Open(@"c:\somefile.bin", FileMode.Open);
BinaryReader reader = new BinaryReader(theFile);
long number = reader.ReadInt64(); byte[] bytes =
reader.ReadBytes(4); string s = reader.ReadString();
reader.Close();
FileStream theFile = File.Open(@"c:\somefile.bin",
FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter writer = new BinaryWriter(theFile);
long number = 100;
byte[] bytes = new byte[] { 10, 20, 50, 100 };
string s = “Toi di hoc";
writer.Write(number); writer.Write(bytes);
writer.Write(s);
BinaryReader và BinaryWriter
BufferedStream thường được sử dụng để tăng hiệu quả đọc ghi
dữ liệu
FileStream newFile = File.Create(@"c:\test.txt");
BufferedStream buffered = new BufferedStream(newFile);
StreamWriter writer = new StreamWriter(buffered);
writer.WriteLine("Some data");
streamWriter.Close();
bufferedStream.Close();
fileStream.Close();
BufferedStream
File đính kèm:
Bài giảng Ngôn ngữ C#.pdf

