By GokiSoft.com| 15:47 05/10/2021|
C Sharp

[Share Code] Tìm hiểu Lambda C# + Đọc ghi File Text C# + Đọc ghi file Object C# - Serializable C#



Nội dung kiến thức:
- Đi nhanh 2 slide còn lại:
- File:
	- File Text
	- File Object
- Chữa bài tập:
=====================================================
Quản lý cửa hàng bán điện thoại:
	Phone:
		Thuộc tính:
			Tên,
			ManufacturerName,
			Năm sản xuất
			Ngay nhập kho
			color
		Phương thức:
			Nhập
			Hiển thị
			Getter/setter & hạm tạo
1. Nhập từ bàn phím: N phone
2. Xem thong tin
3. Luu File
4. Đọc file




#Phone.cs


using System;
namespace Lesson07
{
    [Serializable]
    public class Phone
    {
        public string Name { get; set; }
        public string ManufacturerName { get; set; }
        public string ProductDate { get; set; }
        public string ImportedDate { get; set; }
        public string Color { get; set; }

        public Phone()
        {
        }

        public void Input()
        {
            Console.WriteLine("========== BAT DAU NHAP DU LIEU ============");
            Console.WriteLine("Nhap ten: ");
            Name = Console.ReadLine();

            Console.WriteLine("Nhap nha san xuat: ");
            ManufacturerName = Console.ReadLine();

            Console.WriteLine("Nhap ngay san xuat: ");
            ProductDate = Console.ReadLine();

            Console.WriteLine("Nhap nhap kho: ");
            ImportedDate = Console.ReadLine();

            Console.WriteLine("Nhap mau: ");
            Color = Console.ReadLine();
        }

        public void Display()
        {
            Console.WriteLine("Ten: {0}, nha san xuat: {1}, ngay san xuat: {2}, " +
                "ngay nhap kho: {3}, mau: {4}", Name, ManufacturerName,
                ProductDate, ImportedDate, Color);
        }

        public string GetFileLine()
        {
           return Name + "," + ManufacturerName + "," +
                ProductDate + "," + ImportedDate + "," + Color + "\n";
        }

        public void ParseFileLine(string line)
        {
            string[] elements = line.Split(",");
            Name = elements[0];
            ManufacturerName = elements[1];
            ProductDate = elements[2];
            ImportedDate = elements[3];
            Color = elements[4];
        }
    }
}


#Program.cs


using System;
using System.Collections.Generic;
using System.IO;

namespace Lesson07
{
    delegate double Calculator(double x, double y);

    class Program
    {
        static List<Phone> phoneList;

        static void Main(string[] args)
        {
            phoneList = new List<Phone>();
            int choose;

            do
            {
                ShowMenu();
                choose = int.Parse(Console.ReadLine());

                switch(choose)
                {
                    case 1:
                        Input();
                        break;
                    case 2:
                        Display();
                        break;
                    case 3:
                        //SaveFile();
                        SaveObjectFile();
                        break;
                    case 4:
                        //ReadFile();
                        ReadObjectFile();
                        break;
                    case 5:
                        Console.WriteLine("Thoat!!!");
                        break;
                    default:
                        Console.WriteLine("Nhap sai!!!");
                        break;
                }
            } while (choose != 5);
        }

        private static void ReadObjectFile()
        {
            //deserialize
            using (Stream stream = File.Open(@"phones.dat", FileMode.Open))
            {
                var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                List<Phone> phones = (List<Phone>)bformatter.Deserialize(stream);

                foreach(Phone p in phones)
                {
                    phoneList.Add(p);
                }
            }
            Console.WriteLine("Doc File thanh cong!!!");
        }

        private static void SaveObjectFile()
        {
            //serialize
            using (Stream stream = File.Open(@"phones.dat", FileMode.Create))
            {
                var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                bformatter.Serialize(stream, phoneList);
            }

            Console.WriteLine("Luu File thanh cong!!!");
        }

        private static void ReadFile()
        {
            string content = System.IO.File.ReadAllText(@"phones.txt");
            if(content != null && content != "")
            {
                string[] lines = content.Split("\n");
                foreach(string line in lines)
                {
                    if (line == null || line == "") continue;
                    Phone p = new Phone();
                    p.ParseFileLine(line);

                    phoneList.Add(p);
                }
            }
            Console.WriteLine("Doc File thanh cong!!!");
        }

        private static void SaveFile()
        {
            //Luu Text
            //B1. Dinh hinh du lieu luu -> Cach: moi Phone -> line
            string content = "";
            foreach(Phone p in phoneList)
            {
                content += p.GetFileLine();
            }

            System.IO.File.WriteAllText(@"phones.txt", content);

            Console.WriteLine("Luu File thanh cong!!!");
        }

        private static void Display()
        {
            foreach(Phone p in phoneList)
            {
                p.Display();
            }
        }

        private static void Input()
        {
            Console.WriteLine("Nhap N san pham: ");
            int N = int.Parse(Console.ReadLine());

            for(int i=0;i<N;i++)
            {
                Phone p = new Phone();
                p.Input();

                phoneList.Add(p);
            }
        }

        static void ShowMenu()
        {
            Console.WriteLine("1. Nhap N san pham");
            Console.WriteLine("2. Hien thi");
            Console.WriteLine("3. Luu");
            Console.WriteLine("4. Doc du lieu");
            Console.WriteLine("5. Thoat");
            Console.WriteLine("Chon:");
        }

        static void Test01()
        {
            Calculator TinhTong = delegate (double x, double y)
            {
                return x + y;
            };
            double tong = TinhTong(2.6F, 6.2F);
            Console.WriteLine("Tong: " + tong);

            Calculator TinhHieu = (x, y) => x - y;
            Console.WriteLine("Hieu: " + TinhHieu(6.2F, 2.2F));

            Calculator TinhThuong = (x, y) =>
            {
                if (y == 0)
                {
                    throw new Exception("Khong thuc hien phep chia cho 0");
                }
                return x / y;
            };
            double thuong = TinhThuong(6.2, 2.6);
            Console.WriteLine("Thuong: " + thuong);

            thuong = TinhThuong(6.2, 0);
            Console.WriteLine("Thuong: " + thuong);

            //LINQ: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
            //LINQ: https://www.tutorialspoint.com/linq/index.htm
        }
    }
}


Tags:

Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)