CÁC GIẢI PHÁP LẬP TRÌNH C# - Trang 364

364
Chương 9: File, thư mục, và I/O

private static void Main() {

// Tạo file mới.

FileStream fs = new FileStream("test.txt", FileMode.Create);

// Tạo một writer và chỉ định kiểu mã hóa.

// Kiểu mặc định (UTF-8) hỗ trợ ký tự Unicode,

// nhưng mã hóa các ký tự chuẩn giống như ASCII

StreamWriter w = new StreamWriter(fs, Encoding.UTF8);

// Ghi một số thập phân, một chuỗi, và một ký tự.

w.WriteLine(124.23M);

w.WriteLine("Test string");

w.WriteLine('!');

// Bảo đảm tất cả dữ liệu được ghi từ buffer.

w.Flush();

// Đóng file.

w.Close();

fs.Close();

Console.WriteLine("Press Enter to read the information.");

Console.ReadLine();

// Mở file trong chế độ chỉ-đọc.

fs = new FileStream("test.txt", FileMode.Open);

StreamReader r = new StreamReader(fs, Encoding.UTF8);

// Đọc dữ liệu và chuyển nó về kiểu thích hợp.

Console.WriteLine(Decimal.Parse(r.ReadLine()));

Console.WriteLine(r.ReadLine());

Console.WriteLine(Char.Parse(r.ReadLine()));

r.Close();

fs.Close();