MÔN học cơ sở lập TRÌNH đề tài FILES

31 5 0
MÔN học cơ sở lập TRÌNH đề tài FILES

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

lOMoARcPSD|9234052 BỘ GIÁO DỤC VÀ ĐÀO TẠO TRƯỜNG ĐẠI HỌC KINH TẾ TPHCM KHOA CÔNG NGHỆ THÔNG TIN KINH DOANH MƠN HỌC: CƠ SỞ LẬP TRÌNH BÀI TIỂU LUẬN ĐỀ TÀI: FILES THÀNH PHỐ HỒ CHÍ MINH – NĂM 2021 lOMoARcPSD|9234052 MỤC LỤC GIỚI THIỆU .3 I FILE TEXT …….……………………… Khái quát chung file text……………………… Ghi/ đọc file text……………………………… 2.1 Ghi liệu vào file ………………………………………… 2.2 Đọc liệu từ file… ………………………… .4 Các vấn đề liên quan .4 Một số ví dụ II FILE NHỊ ………………… PHÂN Khái quát chung file nhị phân …………………… Ghi/ đọc file nhị phân ……………………………… 2.1 Ghi liệu vào file 2.2 Đọc liệu từ file Các vấn đề liên quan 11 Một số ví dụ 12 TÀI LIỆU KHẢO 30 KHAM lOMoARcPSD|9234052 TGIỚI THIỆU ệp tin (file) tập hợp loại thông tin liệu người dùng tạo từ máy tính nhằm giúp người dùng lưu trữ liệu cách đơn giản dễ dàng Định dạng file phong phú đa dạng như: lưu trữ văn (txt, doc, ), hiển thị hình ảnh (jpeg, png, ), Tuy nhiên ta tìm hiểu file text file nhị phân cách đọc ghi chúng C# File class tiện ích, cung cấp phương thức tĩnh cho việc tạo, copy, xóa, di chuyển mở file, hỗ trợ tạo đối tượng FileStream I FILE TEXT Khái quát chung file text File text tài liệu văn tiêu chuẩn có chứa văn dạng plain text Hay nói cách khác file text tài liệu văn đơn giản chứa khơng có định dạng File text file thường có txt Trong ngơn ngữ lập trình C#, có thao tác thực với file:  Ghi liệu vào file  Đọc liệu từ file Ghi/ đọc file text Không gian System.IO cung cấp : lớp cho phép người lập trình lấy thơng tin file thư mục (directory), lớp hỗ trợ việc đọc ghi file luồng liệu (stream) Vì để viết chương trình lưu liệu vào file, ta phải thêm dòng tiêu đề: using System.IO; Ngồi ta cịn sử dụng thêm lệnh using System.Text; 2.1 Ghi liệu vào file lOMoARcPSD|9234052 a Ghi cú pháp Trước tiên, ta cần tạo tệp ổ đĩa Sau nhập cú pháp sau: string filename = "\\\\.txt"; StreamWriter sw = new StreamWriter(filename); sw.Write("Xin chao"); sw.Close(); //viết vào sw //đóng sw b Tạo file text hàm CreatText() static string file1 = "\\\\.txt"; StreamWriter sw; //khai bái biến file cần ghi sw = File.CreateText(file1); //tạo file text sw.WriteLine("Xin chao"); sw.Close(); 2.2 Đọc liệu từ file a Cách 1: string filename = "\\\\.txt"; StreamReader sr = new StreamReader(filename); sr.ReadLine(); sr.Close(); b Cách khác: StreamReader sr; //khai báo biến file cần đọc string input; sr = File.OpenText(file1); input = sr.ReadToEnd(); //mở file //đọc toàn file từ đầu đến cuối Console.WriteLine(input); //hiển thị liệu sau đọc  Lưu ý: o Sau ghi/đọc xong cần phải đóng file lại o Chỉ thị static làm cho thành phần khởi tạo được, điều nghĩa thành phần tĩnh khơng thể khỏi tạo => Nếu thị static áp dụng cho lớp lớp khơng thể khởi tạo thể từ khóa new lOMoARcPSD|9234052 Các vấn đề liên quan I/O Class đối tượng BinaryReader Mô tả Đọc liệu gốc (primitive data) từ binary stream file nhị phân BinaryWriter Ghi liệu gốc định dạng nhị phân StreamReader Được sử dụng để đọc ký tự từ stream file text StreamWriter Được sử dụng để ghi ký tự tới stream Một số ví dụ a Kiểm tra xem file có tồn hay khơng Nếu có đọc hiển nội dung file Bài làm using System; using System.IO; using System.Text; namespace luan_cslt { class Program { private const string FILE_NAME = "Test.txt"; static void Main(string[] args) { if (!File.Exists(FILE_NAME)) { Console.WriteLine("{0} does not exist!", FILE_NAME); Console.ReadLine(); return; } using (StreamReader sr = File.OpenText(FILE_NAME)) { string input; while((input = sr.ReadLine())!= null) { Console.WriteLine(input); } Console.WriteLine("The end of the stream"); sr.Close(); } Console.ReadLine(); } } } Kết quả: lOMoARcPSD|9234052 b Ghi liệu sau vào file, đọc hiển thị chúng: This is a text Chao ban Ma so cua ban la: M520.1314 So thu tu cua ban la: 88 Ket thuc Bài làm using System; using System.IO; using System.Text; class Program { static string file1 = "C:\\cs\\test1.txt"; static double a = 520.1314; static int b = 88; static char kt = 'M'; static void Main(string[] args) { using (StreamWriter sw = new StreamWriter(file1)) { sw.WriteLine("This is a text"); sw.WriteLine("Chao ban"); sw.Write("Ma so cua ban la: "); sw.Write(kt); sw.WriteLine(a); sw.Write("So thu tu cua ban la: "); sw.WriteLine(b); sw.Close(); } StreamReader sr1 = new StreamReader(file1); string input; while ((input = sr1.ReadLine()) != null) //file chưa bị rỗng thực lệnh { Console.WriteLine(input); //hiển thị liệu sau đọc } Console.WriteLine("Ket thuc."); sr1.Close(); Console.ReadLine(); } } Kết quả: lOMoARcPSD|9234052 c Nhập số điện thoại phần thưởng Ghi liệu sau vào file, đọc hiển thị chúng: This is a text Chuc mung sdt da trung thuong vui long lien lac voi chung toi qua so dien thoai 1900.xxx de biet them chi tiet Thong bao den day la het Cam on quy khach da theo doi Bài làm using System; using System.IO; using System.Text; class Program { static string file1 = "C:\\cs1\\testfile.txt"; static void Main(string[] args) { Console.Write("Nhap so dien thoai trung thuong: "); int sdt = int.Parse(Console.ReadLine()); Console.Write("Nhap phan thuong: "); string thuong; thuong = Console.ReadLine(); Console.Clear(); StreamWriter sw; sw = File.CreateText(file1); sw.WriteLine("This is a text"); sw.WriteLine("Chuc mung sdt {0} da trung thuong {1}", sdt, thuong); sw.WriteLine("Vui long lien lac voi chung toi qua so dien thoai 1900.xxx de biet them chi tiet"); sw.Close(); StreamReader sr1; string input; sr1 = File.OpenText(file1); input = sr1.ReadToEnd(); Console.WriteLine(input); Console.WriteLine("Thong bao den day la het Cam on quy khach da theo doi."); sr1.Close(); Console.ReadLine(); } } Kết quả: lOMoARcPSD|9234052 d Ghi liệu sau vào file, đọc hiển thị: This is a text Xin chao Toi la robot thong minh Ma hieu cua toi la: M5201314 Toi van dang cai tien vui long cho them Bài làm using System; using System.IO; using System.Text; class Program { static string file1 = "C:\\cs1\\testfile.txt"; static double a = 5201314; static char mahieu = 'M'; static string modau = "xin chao"; static void Main(string[] args) { using (StreamWriter sw = new StreamWriter(file1)) { sw.WriteLine("This is a text"); sw.WriteLine(modau); sw.WriteLine("Toi la robot thong minh"); sw.WriteLine("Ma hieu cua toi la: " + mahieu + a); sw.Close(); } StreamReader sr; string input; sr = File.OpenText(file1); while (true) { input = sr.ReadLine(); if (input == null) break; Console.WriteLine(input); } Console.WriteLine("Toi van dang cai tien vui long cho them."); sr.Close(); Console.ReadLine(); } } lOMoARcPSD|9234052 Kết quả: II FILE NHỊ PHÂN Khái quát chung file nhị phân File nhị phân (Binary file) bao gồm liệu nhị phân lưu trữ máy tính liệu khơng nhị phân chuyển đổi mã hóa thành liệu nhị phân; thường tự nhiên thường trú máy tính, chuyển đổi/ mã hóa để văn đơn giản cần phải truyền qua kết nối mạng/ Internet Tuy nhiên, phương pháp giải mã tệp nhị phân khác khác Việc đọc/ ghi liệu file nhị phân có nhiều ưu điểm file text bảo mật file cao hơn, tiết kiệm khơng gian lưu trữ (số số thực), lưu vào tệp nhanh (khi lượng liệu lớn thể rõ chênh lệch tốc độ hai loại) liệu xác Ghi/ đọc liệu vào file 2.1 Ghi liệu vào file a Ghi liệu vào file kiểu byte byte [] b1 = {1, 2, 3, 4, 255}; // khai báo biến mảng kiểu byte FileStream("C:\\testbin.dat", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); \\ khai báo đối tượng để ghi vào file "testbin.dat" ổ đĩa C foreach (byte bnet in b1) //thực trình ghi phần tử mảng số b1 có kiểu byte { sw.WriteByte(bnext); } sw.Close(); //đóng file b Ghi liệu từ file nhị phân string file1 = "C:\\FileBin1.dat"; FileStream file1; string name; //dữ liệu thành viên lOMoARcPSD|9234052 double salary; //dữ liệu thành viên BinaryWriter wf = new BinaryWriter(file1); file nhị phân //khai báo đối tượng wf cho việc ghi vào wf.Write(name); //ghi thành viên name wf.Write(salary); //ghi thành viên salary 2.2 Đọc liệu từ file a Đọc liệu từ file kiểu byte FileInfo fr = new FileInfo("C:\\testbin.dat"); Stream strm = fr.OpenRead(); //mở file int i; while (true) //sử dụng vòng lặp để đọc { i = strm.ReadByte(); if (i == -1) break; Console.Write("{0, 4}", i); } strm.Close(); //đóng file b Đọc liệu từ file nhị phân FileStream file1; //khai báo file cần đọc BinaryReader rf = new BinaryReader(file1); //khai báo đối tượng rf cho việc đọc name = rf.ReadString(); //đọc thành phần name salary = rf.ReadDouble();  Lưu ý: o Sau ghi/ đọc xong phải đóng file lại o Tùy thuộc vào kiểu khai báo liệu mà ta có hàm đọc liệu khác Kiểu liệu (số nguyên) Khai báo Đọc byte (0 to 255) byte b1; b1 = rf.ReadByte(); sbyte (-128 to 127) sbyte b1; sb1 = rf.ReadSByte(); int (-2,147,483,648 to 2,147,483,647) int a; a = rf.ReadInt32(); 10 lOMoARcPSD|9234052 } public void ReadData(FileStream file1) { BinaryReader rf = new BinaryReader(file1); name = rf.ReadString(); age = rf.ReadInt32(); salary = rf.ReadDouble(); } } class TestFile { static void Main(string[] args) { int n; Console.Write("So du lieu ban muon luu vao file: "); n = Int32.Parse(Console.ReadLine()); Filebin[] p = new Filebin[n]; string filename = "C:\\cs1\\Data.dat"; Console.WriteLine("Ghi du lieu vao file"); FileStream fwr = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Write); for (int i = 0; i < n; i++) { p[i] = new Filebin(); p[i].Input(); p[i].SaveData(fwr); } fwr.Close(); Console.WriteLine("Doc du lieu tu file"); Filebin[] p1 = new Filebin[n]; FileStream fr = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read); for (int i = 0; i < n; i++) { p1[i] = new Filebin(); p1[i].ReadData(fr); p1[i].Show(); } Console.ReadLine(); } } Kết quả: f Xây dựng menu để thực thao tác: Nhập, liệt kê, xóa, sửa, tìm kiếm, bổ sung Bài làm using System; namespace helooooooo { class person { private string name; 17 Downloaded by Heo Út (quangutbin@gmail.com) lOMoARcPSD|9234052 private long ID; private int age; public person() { name = ""; ID = 0; age = 0; } public static int n; public person[] p = new person[100]; public void Input() { for (int i = 0; i < n; i++) { p[i] = new person(); Console.WriteLine("\nperson {0}", i); Console.Write("Enter name: "); p[i].name = Console.ReadLine(); Console.Write("Enter ID: "); p[i].ID = Int64.Parse(Console.ReadLine()); Console.Write("Enter age: "); p[i].age = Int32.Parse(Console.ReadLine()); } } public void Show() { for (int i = 0; i < n; i++) { Console.WriteLine("\nName: {0} \nID: {1} ; age: {2}", p[i].name, p[i].ID, p[i].age); } } public void SearchName() { string name1; Console.Write("Enter name to search: "); name1 = Console.ReadLine(); for (int i = 0; i < n; i++) { if (String.Compare(name1, p[i].name) == 0) { Console.WriteLine("\nName: {0} \nID: {1} ; age: {2}", p[i].name, p[i].ID, p[i].age); } } } public void SearchID() { long id1; Console.Write("Enter ID to search: "); id1 = Int64.Parse(Console.ReadLine()); for (int i = 0; i < n; i++) { if (id1 == p[i].ID) { Console.WriteLine("\nName: {0} \nID: {1} ; age: {2}", p[i].name, p[i].ID, p[i].age); } } } public void Delete() { 18 Downloaded by Heo Út (quangutbin@gmail.com) lOMoARcPSD|9234052 Console.Write("You want to delete by ID or name (I/N): "); string select = Console.ReadLine(); if (select.ToUpper() == "I") { Console.Write("Enter ID to delete: "); long id1 = Int64.Parse(Console.ReadLine()); for (int i = 0; i < n; i++) { if (id1 == p[i].ID) { Console.WriteLine("\nName: {0} \nID: {1} ; age: {2}", p[i].name, p[i].ID, p[i].age); while (i < n) { p[i] = p[i + 1]; i++; } } n = n - 1; } } else if (select.ToUpper() == "N") { Console.Write("Enter name to delete: "); string name2 = Console.ReadLine(); for (int i = 0; i < n; i++) { if (name2 == p[i].name) { Console.WriteLine("\nName: {0} \nID: {1} ; age: {2}", p[i].name, p[i].ID, p[i].age); while (i < n) { p[i] = p[i + 1]; i++; } } n = n - 1; } } else { Console.WriteLine("Error !!!"); } } public void Edit() { Console.Write("You want to edit by ID or name (I/N): "); string select = Console.ReadLine(); if (select.ToUpper() == "N") { Console.Write("Enter name to edit: "); string name1 = Console.ReadLine(); for (int i = 0; i < n; i++) { if (String.Compare(name1, p[i].name) == 0) { Console.WriteLine("\nName: {0} \nID: {1} ; age: {2}", p[i].name, p[i].ID, p[i].age); Console.WriteLine("\nperson {0}", i); Console.Write("Enter name: "); p[i].name = Console.ReadLine(); Console.Write("Enter ID: "); p[i].ID = Int64.Parse(Console.ReadLine()); Console.Write("Enter age: "); p[i].age = Int32.Parse(Console.ReadLine()); } } 19 Downloaded by Heo Út (quangutbin@gmail.com) lOMoARcPSD|9234052 } else if (select.ToUpper() == "I") { Console.Write("Enter ID to edit: "); long id2 = Int64.Parse(Console.ReadLine()); for (int i = 0; i < n; i++) { if (id2 == p[i].ID) { Console.WriteLine("\nName: {0} \nID: {1} ; age: {2}", p[i].name, p[i].ID, p[i].age); Console.WriteLine("\nperson {0}", i); Console.Write("Enter name: "); p[i].name = Console.ReadLine(); Console.Write("Enter ID: "); p[i].ID = Int64.Parse(Console.ReadLine()); Console.Write("Enter age: "); p[i].age = Int32.Parse(Console.ReadLine()); } } } else { Console.WriteLine("Error !!!"); } } public void Append() { p[n] = new person(); Console.Write("Enter name: "); p[n].name = Console.ReadLine(); Console.Write("Enter ID: "); p[n].ID = Int64.Parse(Console.ReadLine()); Console.Write("Enter age: "); p[n].age = Int32.Parse(Console.ReadLine()); n = n + 1; } public static void Main() { person per = new person(); int choice = 0; { Console.WriteLine("\n MENU "); Console.WriteLine("1 Input Data "); Console.WriteLine("2 List All "); Console.WriteLine("3 Edit "); Console.WriteLine("4 Search Name "); Console.WriteLine("5 Search ID "); Console.WriteLine("6 Delete "); Console.WriteLine("7 Append "); Console.WriteLine("8 Exit "); Console.Write("Enter choice: "); choice = Int32.Parse(Console.ReadLine()); switch (choice) { case 1: { Console.Write("Enter number of persons: "); n = Int32.Parse(Console.ReadLine()); per.Input(); break; } case 2: { per.Show(); break; 20 Downloaded by Heo Út (quangutbin@gmail.com) lOMoARcPSD|9234052 } case 3: { per.Edit(); break; } case 4: { per.SearchName(); break; } case 5: { per.SearchID(); break; } case 6: { per.Delete(); break; } case 7: { per.Append(); break; } case 8: continue; } } while (choice != 8); } } } Kết quả: 21 Downloaded by Heo Út (quangutbin@gmail.com) lOMoARcPSD|9234052 g Viết chương trình để lưu liệu vào file Bài làm using System; using System.IO; using System.Collections; 22 Downloaded by Heo Út (quangutbin@gmail.com) lOMoARcPSD|9234052 namespace cslt { class Phone { private private private private private private ulong _phoneNumber; string _fullName; string _address; int _noOfLine; string _type; string _organization; public Phone(ulong _phoneNumber, string _fullName, string _address, int _noOfLine, string _type, string _organization) { this._phoneNumber = _phoneNumber; this._fullName = _fullName; this._address = _address; this._noOfLine = _noOfLine; this._type = _type; this._organization = _organization; } public Phone() : this(0, "", "", 0, "", "") { } public ulong _PhoneNumber { get { return _phoneNumber; } set { _phoneNumber = value; } } public string FullName { get { return _fullName; } set { _fullName = value; } } public string Address { get { return this._address; } set { _address = value; } } public int noOfLine { get { return _noOfLine; } set { _noOfLine = value; } } public string Type { get { return _type; } set { _type = value; } } public string Organization { get { return _organization; } set { _organization = value; } } public void Input() { Console.Write("Phone number: "); _phoneNumber = UInt64.Parse(Console.ReadLine()); Console.Write("Full name: "); _fullName = Console.ReadLine(); Console.Write("Address: "); 23 Downloaded by Heo Út (quangutbin@gmail.com) lOMoARcPSD|9234052 _address = Console.ReadLine(); Console.Write("No of line: "); _noOfLine = Int32.Parse(Console.ReadLine()); Console.Write("Type: "); _type = Console.ReadLine(); Console.Write("Organization: "); _organization = Console.ReadLine(); } public void Display() { Console.WriteLine("Telephone Number: \t{0} \t\t\tLines: {0}", _phoneNumber, _noOfLine); Console.WriteLine("Name/Organization: \t" + _fullName + " /" + _organization); Console.WriteLine("Address: \t\t" + _address); Console.WriteLine("Type: \t\t\t" + _type); } public override string ToString() { return (String.Format("Phone: {0} \nName: {1} \nAddress: {2} \nLine: {3} \nType: {4} \nOrg: {5} \n", _phoneNumber, _fullName, _address, _noOfLine, _type, _organization)); } public void Save(BinaryWriter bw) { bw.Write(_phoneNumber); bw.Write(_fullName); bw.Write(_address); bw.Write(_noOfLine); bw.Write(_type); bw.Write(_organization); } public void Load(BinaryReader br) { _phoneNumber = br.ReadUInt64(); _fullName = br.ReadString(); _address = br.ReadString(); _noOfLine = br.ReadInt32(); _type = br.ReadString(); _organization = br.ReadString(); } } class PhoneBook { ArrayList data = new ArrayList(); public Phone this[int i] { get { if ((-1 < i) && (i < data.Count)) return (Phone)data[i]; else throw new IndexOutOfRangeException("Index out of ranger"); } set { if ((-1 < i) && (i < data.Count)) data[i] = value; else if (i == data.Count) data.Add(value); else throw new IndexOutOfRangeException("Index out of range"); } } public void Clear() 24 Downloaded by Heo Út (quangutbin@gmail.com) lOMoARcPSD|9234052 { data.Clear(); } public void Delete(int index) { if ((-1 < index) && (index < data.Count)) { data.RemoveAt(index); Console.WriteLine("Done"); } else throw new IndexOutOfRangeException("Nothing to delete"); } public void Edit(int index) { if ((-1 < index) && (index < data.Count)) { this[index].Display(); this[index].Input(); Console.WriteLine("Done"); } else throw new IndexOutOfRangeException("Nothing to edit"); } public void Search(string name) { int found = 0; int[] indexArray = new int[data.Count]; int j = 0; for (int i = 0; i < data.Count; ++i) { if (this[i].FullName.ToUpper() == name.ToUpper()) { ++found; indexArray[j++] = i; } } if (found > 0) { Console.WriteLine("Found phone(s): {0}", found); for (int k = 0; k < found; ++k) { Console.WriteLine("Index of the phobe info: {0} ", indexArray[k]); Console.WriteLine(this[indexArray[k]].ToString()); } } else Console.WriteLine("Not found"); } public void Search(ulong _phoneNumber) { for (int i = 0; i < data.Count; ++i) { if (this[i]._PhoneNumber == _phoneNumber) { Console.WriteLine("Index of the phone info: {0}", i); Console.WriteLine(this[i].ToString()); return; } } Console.WriteLine("Not found"); } public int Count { 25 Downloaded by Heo Út (quangutbin@gmail.com) lOMoARcPSD|9234052 get { return data.Count; } } } class App { static int index = -1; static PhoneBook list = new PhoneBook(); public static int Main() { while (true) { int choice = Menu(); switch (choice) { case 1: { Add(); break; } case 2: { Edit(); Console.ReadLine(); break; } case 3: { Delete(); Console.ReadLine(); break; } case 4: { Search(); Console.ReadLine(); break; } case 5: { Display(); break; } case 6: { Save(); break; } case 7: { Load(); break; } case 8: { EmergencyNumbers(); break; } case 9: { return 0; } } } static int Menu() { Console.WriteLine("\n\n========= MENU ========="); 26 Downloaded by Heo Út (quangutbin@gmail.com) lOMoARcPSD|9234052 Console.WriteLine("1 Add a Phone"); Console.WriteLine("2 Edit a Phone"); Console.WriteLine("3 Delete a Phone"); Console.WriteLine("4 Search a Phone"); Console.WriteLine("5 Display PhoneBook"); Console.WriteLine("6 Save to file"); Console.WriteLine("7 Load from file"); Console.WriteLine("8 Display Emergency Numbers"); Console.WriteLine("9 Exit"); int ch = 0; while ((ch < 1) || (ch > 9)) { try { Console.Write("\nEnter your choice: "); ch = Int32.Parse(Console.ReadLine()); } catch { continue; } } return ch; } static void Add() { bool next = true; while (next) { Console.WriteLine("\nEnter Phone info: "); Phone phone = new Phone(); phone.Input(); list[++index] = phone; Console.Write("Do you want to continue ? (y/n): "); string choice = Console.ReadLine(); if (choice.ToUpper() == "Y") next = true; else next = false; } } static void Display() { for (int i = 0; i < list.Count; ++i) { list[i].Display(); Console.ReadLine(); } } static void Search() { Console.Write("Search by Name of PhoneNumber (N/P): "); string select = Console.ReadLine(); if (select.ToUpper() == "N") { Console.Write("Enter Name: "); string name = Console.ReadLine(); list.Search(name); } else { Console.Write("Enter Phone Number: "); ulong tel = UInt64.Parse(Console.ReadLine()); list.Search(tel); } } 27 Downloaded by Heo Út (quangutbin@gmail.com) lOMoARcPSD|9234052 static void Edit() { Console.Write("\nEnter index of Phone to edit: "); int i = Int32.Parse(Console.ReadLine()); list.Edit(i); } static void Delete() { Console.Write("\nEnter index of Phone to delete: "); int i = Int32.Parse(Console.ReadLine()); list.Delete(i); } static void Save() { Console.Write("\nEnter file name: "); string fileName = Console.ReadLine(); if (File.Exists(fileName)) File.Delete(fileName); FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Write); BinaryWriter bw = new BinaryWriter(fs); for (int i = 0; i < list.Count; ++i) list[i].Save(bw); bw.Close(); fs.Close(); } static void Load() { Console.Write("\nEnter file name: "); string fileName = Console.ReadLine(); if (File.Exists(fileName)) { list.Clear(); FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader br = new BinaryReader(fs); int i = -1; while (br.PeekChar() > -1) { Phone phone = new Phone(); phone.Load(br); list[++i] = phone; br.Close(); fs.Close(); } } else throw new FileNotFoundException("there is no file", fileName); } static void EmergencyNumbers() { Console.WriteLine("Police: 113"); Console.WriteLine("Fire: 114"); Console.WriteLine("Ambulance: 115"); } } } Kết quả: 28 Downloaded by Heo Út (quangutbin@gmail.com) lOMoARcPSD|9234052 29 Downloaded by Heo Út (quangutbin@gmail.com) lOMoARcPSD|9234052 TÀI LIỆU KHAM KHẢO  Sách Lập trình C# từ đến nâng cao – Phạm Công Ngô  Ebook (lms)  Một số tài liệu khác: https://webbachthang.com/file-la-gi-khai-niem-va-cau-truc-cua-file-nhu-nao/ https://openplanning.net/10453/thao-tac-voi-tap-tin-va-thu-muc-trong-csharp https://docs.microsoft.com/vi-vn/dotnet/api/system.io.filemode?view=netframework4.8 https://docs.microsoft.com/en-us/dotnet/api/system.io.fileaccess?view=net-6.0 https://nguyenvanhieu.vn/doc-ghi-file-trong-c-sharp/ 30 Downloaded by Heo Út (quangutbin@gmail.com) lOMoARcPSD|9234052 31 Downloaded by Heo Út (quangutbin@gmail.com) ... txt Trong ngơn ngữ lập trình C#, có thao tác thực với file:  Ghi liệu vào file  Đọc liệu từ file Ghi/ đọc file text Không gian System.IO cung cấp : lớp cho phép người lập trình lấy thơng tin... Heo Út (quangutbin@gmail.com) lOMoARcPSD|9234052 TÀI LIỆU KHAM KHẢO  Sách Lập trình C# từ đến nâng cao – Phạm Công Ngô  Ebook (lms)  Một số tài liệu khác: https://webbachthang.com/file-la-gi-khai-niem-va-cau-truc-cua-file-nhu-nao/... byte FileStream("C:\\testbin.dat", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); \\ khai báo đối tượng để ghi vào file "testbin.dat" ổ đĩa C foreach (byte bnet in b1) //thực trình

Ngày đăng: 12/12/2022, 08:40

Tài liệu cùng người dùng

Tài liệu liên quan