By GokiSoft.com|
08:38 14/10/2021|
C Sharp
[Video] Tìm hiểu File C Sharp | File Text C Sharp | File Binary C Sharp | Serializable C Sharp - C2009G
File -> C#
- File Text:
- File nhi phan (binary) -> Luu object | list object -> file
#Program.cs
using System;
using System.Collections.Generic;
using System.IO;
namespace Lesson04
{
class Program
{
static void Main(string[] args)
{
//Test01();
//Test02();
Test03();
}
static void Test03()
{
List<Book> books = new List<Book>();
//deserialize
using (Stream stream = File.Open(@"books.dat", FileMode.Open))
{
var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
books = (List<Book>)bformatter.Deserialize(stream);
}
foreach(Book book in books)
{
Console.WriteLine(book.GetFileLine());
}
}
static void Test02()
{
List<Book> books = new List<Book>();
books.Add(new Book("A1", 1));
books.Add(new Book("A2", 10));
books.Add(new Book("A3", 6));
//Save
//serialize
using (Stream stream = File.Open(@"books.dat", FileMode.Create))
{
var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bformatter.Serialize(stream, books);
}
}
/**
* FILE Text
*/
static void Test01()
{
string content = "Sinh vien Aptech";
//Luu du lieu
System.IO.File.WriteAllText(@"test01.txt", content);
//Luu mang vao file
string[] lines = { "line 1", "line 2", "line 3" };
System.IO.File.WriteAllLines(@"test02.txt", lines);
//Luu mang object -> file
List<Book> books = new List<Book>();
books.Add(new Book("A1", 1));
books.Add(new Book("A2", 10));
books.Add(new Book("A3", 6));
//C1: Chuyen books -> string
string data = "";
foreach(Book book in books)
{
data += book.GetFileLine();
}
System.IO.File.WriteAllText(@"test03.txt", data);
//Doc noi dung
content = System.IO.File.ReadAllText(@"test03.txt");
Console.WriteLine(content);
}
}
}
#Book.cs
using System;
namespace Lesson04
{
[Serializable]
public class Book
{
public string Name { get; set; }
public float Price { get; set; }
public Book()
{
}
public Book(string name, float price)
{
Name = name;
Price = price;
}
public string GetFileLine()
{
return Name + "," + Price + "\n";
}
}
}
Tags:
Phản hồi từ học viên
5
(Dựa trên đánh giá ngày hôm nay)