Có thể sử dụng được các lớp FileStream và lớp BinaryFormatter để đọc và viết các đối tượng vào trong các File.. BinaryFormatter sử dụng 2 phương thức Serialize và Deserialize để viết
Trang 1Chương 8 Files và Streams
8.1 Files và Streams
8.2 Lớp File và lớp Directory
8.3 File truy xuất tuần tự
8.4 File truy xuất ngẫu nhiên
Trang 28.1 Files và Streams
Mục đích của nghiên cứu phần này:
Cung cấp khả năng khởi tạo, đọc, viết và khả năng cập nhật File.
Hiểu được luồng thông tin (Stream) trong C#.
Có thể sử dụng lớp File và thư mục.
Có thể sử dụng được các lớp FileStream và lớp BinaryFormatter
để đọc và viết các đối tượng vào trong các File.
Nắm vững việc xử lý các File truy xuất tuần tự và File truy xuất
ngẫu nhiên.
Trang 3 File được sử dụng như bộ nhớ ngoài để lưu trữ với số lượng lớn
dữ liệu,và có thể giữ lại dữ liệu thậm chí sau khi chương trình kết thúc
Mỗi File kết thúc với một kí tự đánh dấu kết thúc File hoặc một số
Byte xác định được ghi trong hệ thống lưu trữ quản lý cấu trúc dữ liệu
Files ?
Phần tử đầu tiên của File
Phần tử cuối (thứ n) của File
Dấu hiệu kết thúc File
Trang 4Cấu tạo của File trong lưu trữ
Trang 5Stream ?
Stream (luồng) là luồng của thông tin, chứa thông tin sẽ được
chuyển qua, còn tập tin thì để lưu trữ thông tin.
Trang 6Khi một File được mở ra:
C# sẽ tạo một đối tượng.
Nối luồng thông tin với đối tượng này
Có 3 đối tượng stream:
Console.In : trả về một đối tượng stream vào chuẩn.
Console.Out: trả về một đối tượng stream ra chuẩn.
Console.Error: trả về một đối tượng stream thông báo lỗi chuẩn.
Trang 7BinaryFormatter sử dụng 2 phương thức Serialize và Deserialize để
viết và đọc đối tượng từ trong luồng:
Serialize :chuyển đổi một đối tượng sang một định dạng, và
có thể được viết vào File mà không mất dữ liệu.
Deserialize : đọc dữ liệu đã định dạng từ một File và chuyển
nó về dạng ban đầu
System.IO.Stream cho phép thể hiện dưới dạng bit của stream:
FileStream: đọc và viết từ File truy xuất trình tự và ngẫu nhiên:
MemoryStream : chuyển đổi dữ liệu trực tiếp với bộ nhớ.
BufferedStream : sử dụng bộ nhớ đệm để chuyển dữ liệu.
Trang 88.2 Lớp File và lớp Directory
Thông tin được lưu trữ trên các files
Files được tổ chức thành các thư mục
Lớp Directory dùng để thao tác các thư mục
Lớp File dùng để thao tác trên các files
Chỉ có phương thức tĩnh,không thể khởi tạo đối tượng File
Trang 98.2 Lớp File và lớp Directory
Trang 108.2 Lớp File và lớp Directory
Trang 1112 // displays contents of files and directories
13 public class FileTestForm : System.Windows.Forms.Form
14 {
15 private System.Windows.Forms.Label directionsLabel;
16
17 private System.Windows.Forms.TextBox outputTextBox;
18 private System.Windows.Forms.TextBox inputTextBox;
30 // invoked when user presses key
31 private void inputTextBox_KeyDown(
32 object sender, System.Windows.Forms.KeyEventArgs e )
33 {
Textbox để nhập đường dẫn file và thư mục
Kiểm soát việc
gõ phím enter
FileTest.cs
Trang 1234 // determine whether user pressed Enter key
35 if ( e.KeyCode == Keys.Enter )
45 // get file's creation date,
46 // modification date, etc
47 outputTextBox.Text = GetInformation( fileName );
48
49 // display file contents through StreamReader
50 try
51 {
52 // obtain reader and file contents
53 StreamReader stream = new StreamReader( fileName );
59 MessageBox.Show( "File Error", "File Error",
60 MessageBoxButtons.OK, MessageBoxIcon.Error );
61 }
62 }
63
64 // determine whether fileName is a directory
65 else if ( Directory.Exists( fileName ) )
Kiểm tra sự tồn tại file fileName
Nếu file tồn tại,lấy
và đưa ra thông tin
Tạo StreamReader
để đọc text từ file Gọi method
Trang 1369
70 // get directory's creation date,
71 // modification date, etc
72 outputTextBox.Text = GetInformation( fileName );
73
74 // obtain file/directory list of specified directory
75 directoryList = Directory.GetDirectories( fileName );
76
77 outputTextBox.Text +=
78 "\r\n\r\nDirectory contents:\r\n";
79
80 // output directoryList contents
81 for ( int i = 0; i < directoryList.Length; i++ )
88 " does not exist", "File Error",
89 MessageBoxButtons.OK, MessageBoxIcon.Error );
95 // get information on file or directory
96 private string GetInformation( string fileName )
97 {
98 // output that file or directory exists
99 string information = fileName + " exists\r\n\r\n";
Nếu tồn tại,lấy và đưa
ra thông tin thư mục
Lấy các thư mục con Đưa ra các thư mục con
Báo lỗi nếu không tồn tại file có tên được nhập
FileTest.cs
Trang 14104
105 // output when file or directory was last modified
106 information += "Last modified: " +
107 File.GetLastWriteTime( fileName ) + "\r\n";
108
109 // output when file or directory was last accessed
110 information += "Last accessed: " +
Lần cuối truy cập file
Tr ả lại thông tin file
FileTest.cs
Trang 15FileTest.cs Program Output
Trang 168.3 File truy xuất tuần tự
C# không có áp đặt nào lên File Do vậy,ta phải xây dựng định dạng
dữ liệu cho File (sử dụng các bản ghi).
Để lấy dữ liệu từ File này,chương trình thường bắt đầu từ điểm đầu
tiên (0),tìm và đọc tuần tự cho đến khi dữ liệu được tìm thấy.
File dạng này khả năng đáp ứng không cao.
Lớp BinaryFormatter kết hợp với một đối tượng Stream để thực
hiện ở đầu vào/ra của đối tượng
Trang 17Tạo khả năng truy cập File(viết vào File)
Mở một File đã tồn tại hoặc tạo File mới
Tạo một đối tượng
của luồng BinaryFormatter Luồng cần thiết cho
việc tạo File
Ghi dữ liệu vào File
Record là một Struct nào đó cần ghi vào File
Nhớ là phải đóng File vào
Phương thức để ghi
dữ liệu vào File
8.3.1 Tạo File truy xuất tuần tự Các không gian tên cần thiết
Trang 1815 public System.Windows.Forms.Label accountLabel;
16 public System.Windows.Forms.TextBox accountTextBox;
17
18 public System.Windows.Forms.Label firstNameLabel;
19 public System.Windows.Forms.TextBox firstNameTextBox;
20
21 public System.Windows.Forms.Label lastNameLabel;
22 public System.Windows.Forms.TextBox lastNameTextBox;
23
24 public System.Windows.Forms.Label balanceLabel;
25 public System.Windows.Forms.TextBox balanceTextBox;
26
27 // number of TextBoxes on Form'
28 protected int TextBoxCount = 4;
29
Labels Textboxes
BankUI.cs
Trang 1930 // enumeration constants specify TextBox indices
31 public enum TextBoxIndices
48 // clear all TextBoxes
49 public void ClearTextBoxes()
50 {
51 // iterate through every Control on form
52 for ( int i = 0; i < Controls.Count; i++ )
BankUI.cs
Trang 2065
66 // set text box values to string array values
67 public void SetTextBoxValues( string[] values )
68 {
69 // determine whether string array has correct length
70 if ( values.Length != TextBoxCount )
71 {
72 // throw exception if not correct length
73 throw( new ArgumentException( "There must be " +
74 (TextBoxCount + 1) + " strings in the array" ) );
93 // return text box values as string array
94 public string[] GetTextBoxValues()
95 {
96 string[] values = new string[ TextBoxCount ];
97
Phương thức để thiết lập giá trị của textboxes
Phương thức để lấy giá trị của textboxes
Trang 2198 // copy text box fields to string array
99 values[ ( int )TextBoxIndices.ACCOUNT ] =
Trang 229 private int account;
10 private string firstName;
11 private string lastName;
12 private double balance;
13
14 // default constructor sets members to default values
15 public Record() : this( 0, "", "", 0.0 )
16 {
17 }
18
19 // overloaded constructor sets members to parameter values
20 public Record( int accountValue, string firstNameValue,
21 string lastNameValue, double balanceValue )
Nói với trình biên dịch là các đối
tượng của lớp Record có thể xuất
hiện như một tập các bits
Dữ liệu đi vào record
Thiết lập các thành phần là 0
Thiết lập các thành phần là các tham số
Record.cs
Trang 23Record.cs
Trang 24Record.cs
Trang 2520 private System.Windows.Forms.Button saveButton;
21 private System.Windows.Forms.Button enterButton;
22 private System.Windows.Forms.Button exitButton;
23
24 private System.ComponentModel.Container components = null;
25
26 // serializes Record in binary format
27 private BinaryFormatter formatter = new BinaryFormatter();
28
29 // stream through which serializable data is written to file
30 private FileStream output;
31
CreateSequentialAccessFile.cs
Trang 2640 // invoked when user clicks Save button
41 private void saveButton_Click(
42 object sender, System.EventArgs e )
43 {
44 // create dialog box enabling user to save file
45 SaveFileDialog fileChooser = new SaveFileDialog();
46 DialogResult result = fileChooser.ShowDialog();
47 string fileName; // name of file to save data
48
49 // allow user to create file
50 fileChooser.CheckFileExists = false;
51
52 // exit event handler if user clicked "Cancel"
53 if ( result == DialogResult.Cancel )
59 // show error if user specified invalid file
60 if ( fileName == "" || fileName == null )
61 MessageBox.Show( "Invalid File Name", "Error",
62 MessageBoxButtons.OK, MessageBoxIcon.Error );
Tạo đối tượng SaveFileDialog Hiển thị
SaveFileDialog
Kiểm tra nếu người dùng muốn thoát Nhận tên file
để save
CreateSequentialAccessFile.cs
Trang 2768 // open file with write access
69 output = new FileStream( fileName,
70 FileMode.OpenOrCreate, FileAccess.Write );
80 // notify user if file does not exist
81 MessageBox.Show( "File Does Not Exist", "Error",
82 MessageBoxButtons.OK, MessageBoxIcon.Error );
83 }
84 }
85 } // end method saveButton_Click
86
87 // invoke when user clicks Enter button
88 private void enterButton_Click(
89 object sender, System.EventArgs e )
90 {
91 // store TextBox values string array
92 string[] values = GetTextBoxValues();
93
94 // Record containing TextBox values to serialize
95 Record record = new Record();
96
Phương thức ghi dữ liệu khi người dùng click enter
CreateSequentialAccessFile.cs
Trang 2897 // determine whether TextBox account field is empty
98 if ( values[ ( int )TextBoxIndices.ACCOUNT ] != "" )
99 {
100 // store TextBox values in Record and serialize Record
101 try
102 {
103 // get account number value from TextBox
104 int accountNumber = Int32.Parse(
105 values[ ( int )TextBoxIndices.ACCOUNT ] );
115 values[ ( int )TextBoxIndices.LAST ];
116 record.Balance = Double.Parse( values[
117 ( int )TextBoxIndices.BALANCE ] );
118
119 // write Record to FileStream (serialize object)
120 formatter.Serialize( output, record );
121 }
122 else
123 {
124 // notify user if invalid account number
125 MessageBox.Show( "Invalid Account Number", "Error",
126 MessageBoxButtons.OK, MessageBoxIcon.Error );
Ghi dữ liệu vào file
CreateSequentialAccessFile.cs
Trang 29130 // notify user if error occurs in serialization
131 catch( SerializationException )
132 {
133 MessageBox.Show( "Error Writing to File", "Error",
134 MessageBoxButtons.OK, MessageBoxIcon.Error );
140 MessageBox.Show( "Invalid Format", "Error",
141 MessageBoxButtons.OK, MessageBoxIcon.Error );
149 // invoked when user clicks Exit button
150 private void exitButton_Click(
151 object sender, System.EventArgs e )
CreateSequentialAccessFile.cs
Trang 30162 // notify user of error closing file
163 catch( IOException )
164 {
165 MessageBox.Show( "Cannot close file", "Error",
166 MessageBoxButtons.OK, MessageBoxIcon.Error );
Trang 31Program Output
SaveFileDialogue
Files và thư mục
Trang 32Program Output
Trang 33Program Output
Trang 34Program Output
Trang 358.3.2 Đọc File truy xuất tuần tự
Đọc dữ liệu tuần tự từ một file
Chương trình thường bắt đầu ở đầu file và đọc dữ liệu liên tiếp cho tới khi thấy dữ liệu mong muốn
Đôi khi cần làm việc này một vài lần trong suốt thời gian chạy
chương trình
Con trỏ vị trí file :
Chỉ tới byte kế tiếp sẽ được đọc hay ghi dữ liệu
Có thể chỉ tới bất kỳ điểm nào trong file
RichTextBox:
LoadFile: phương thức để hiển thị nội dung file
Find: phương thức tìm kiếm những xâu riêng
Có thể hiển thị nhiều dòng văn bản
Trang 368.3.2 Đọc File truy xuất tuần tự Phương thức để ghi dữ liệu vào
cho việc mở File
Mở một File đã tồn tại để đọc
Tạo khả năng truy cập File(đọc từ File)
Đọc dữ liệu
từ File
Tuyệt đối nhớ là phải đóng File vào
Trang 3725 // stream through which serializable data are read from file
26 private FileStream input;
27
28 // object for deserializing Record in binary format
29 private BinaryFormatter reader = new BinaryFormatter();
Trang 3836
37 // Visual Studio NET generated code
38
39 // invoked when user clicks Open button
40 private void openButton_Click(
41 object sender, System.EventArgs e )
42 {
43 // create dialog box enabling user to open file
44 OpenFileDialog fileChooser = new OpenFileDialog();
45 DialogResult result = fileChooser.ShowDialog();
46 string fileName; // name of file containing data
47
48 // exit event handler if user clicked Cancel
49 if ( result == DialogResult.Cancel )
56 // show error if user specified invalid file
57 if ( fileName == "" || fileName == null )
58 MessageBox.Show( "Invalid File Name", "Error",
59 MessageBoxButtons.OK, MessageBoxIcon.Error );
60 else
61 {
62 // create FileStream to obtain read access to file
63 input = new FileStream( fileName, FileMode.Open,
70 } // end method openButton_Click
Khởi tạo OpenFilelDialog Hiển thị
OpenFileDialog
Tạo đối tượng FileStream để nhập với thuộc tính read only
ReadSequentialAccessFile.cs
Trang 3971
72 // invoked when user clicks Next button
73 private void nextButton_Click(
74 object sender, System.EventArgs e )
83 // store Record values in temporary string array
84 string[] values = new string[] {
Hiển thị Record trong TextBoxes
Exception kiểm soát trường hợp không còn records
Đóng FileStream
ReadSequentialAccessFile.cs
Trang 40106 ClearTextBoxes();
107
108 // notify user if no Records in file
109 MessageBox.Show( "No more records in file", "",
110 MessageBoxButtons.OK, MessageBoxIcon.Information );
ReadSequentialAccessFile.cs