در این کد نحوه ی ذخیره ی اطلاعات درون کلاس به دو صورت باینری و XML قرار داده شده است. در حالت باینری اطلاعات درون کلاس با نوتپد خوانده نمیشود ولی در حالت xml میتوان به محتویات داخل کلاس دست یافت.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
car a = new car() { speed = 1, weight = 1 };
WriteToBinaryFile<car>("Car", a);
car c = ReadFromBinaryFile<car>("Car");
}
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
Stream stream= File.Open(filePath, append ? FileMode.Append : FileMode.Create);// new FileStream(filePath, FileMode.Create);
// stream.WriteTimeout = 5000;
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, objectToWrite);
}
public static T ReadFromBinaryFile<T>(string filePath)
{
using (Stream stream = File.Open(filePath, FileMode.Open))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
return (T)binaryFormatter.Deserialize(stream);
}
}
public static void Save<A>(A listofa)
{
string path = "filepath";
FileStream outFile = File.Create(path);
XmlSerializer formatter = new XmlSerializer(typeof(A));
formatter.Serialize(outFile, listofa);
}
public static A Load<A>()
{
string file = "filepath";
A listofa;
XmlSerializer formatter = new XmlSerializer(typeof(A));
FileStream aFile = new FileStream(file, FileMode.Open);
byte[] buffer = new byte[aFile.Length];
aFile.Read(buffer, 0, (int)aFile.Length);
MemoryStream stream = new MemoryStream(buffer);
return (A)formatter.Deserialize(stream);
}
}
[Serializable]
class car
{
public double speed;
public double weight;
}
}