1.BinaryReader class and BinaryWriter class
BinaryReader
And BinaryWriter
can be used for binary input/output, that is, to read and write basic data types (such as int
, double
etc.) instead of the original byte types. BinaryReader
And BinaryWriter
is not a Stream
subclass of the class, but it is a Stream
flow packaging, in the configuration BinaryReader
, and BinaryWriter
an object, a required Stream
object as its argument. Such as:
new BinaryReader(myStream);
In fact, these two types mainly convert between basic types and raw bytes, so they need to deal with some basic Stream
objects that can perform I/O on bytes , such as FileStream or MemoryStream
. Both types have an BaseStream
attribute through which Stream
a reference to the basic object can be obtained . The following are BinaryWriter
some methods of the class:
BinaryReader
with BinaryWriter
very similar functions, there are multiple ReadXXX()
methods with different names . For example, BinaryWriter
there can be Write(Int16)
methods and Write(Char)
methods in, but BinaryReader
only ReadInt16()
methods and ReadChar()
methods in zhong. Because, when performing a write operation, the writer object can infer what is written based on the parameters of Write(); when performing a read operation, in the face of each byte stream, the reader object does not know how to treat these bytes Organized together. You must call a specific function to be able to tell the reader object how to organize the byte stream together.
2. Binary input/output with Stream
BinaryReader
And BinaryWriter
can Stream
be packaged to input/output binary raw data.
For example, write data to a file in binary format, and then read data from the file:
using System;
using System.IO;
class Test
{
static void Main(){
try {
FileStream ds = new FileStream("test_binary.dat", FileMode.Create, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(ds);
// Write some data to the stream;
bw.Write("A string");
bw.Write(142);
bw.Write(97.4);
bw.Write(true);
// Open it for reading;
BinaryReader br = new BinaryReader(ds);
// Move back to the start;
br.BaseStream.Seek(0, SeekOrigin.Begin);
// Read the data
Console.WriteLine(br.ReadString());
Console.WriteLine(br.ReadInt32());
Console.WriteLine(br.ReadDouble());
Console.WriteLine(br.ReadBoolean());
} catch (Exception e) {
Console.WriteLine("Exception:" + e.ToString());
}
}
}
In the example, an FileStream
object is created to operate on the file. The second parameter when creating an object determines how the file is opened. In this example, is FileMode.Create
, which means to create a new file or overwrite an existing file with the same name. The third parameter determines the access permissions of the file, used in this example FileAccess.ReadWrite
, to read and write the file.
FileStream
You can perform operations on your own, which is usually inconvenient, so it is FileStream
often packaged into other classes that can convert bytes. As above, a BinaryWriter
class is used that can receive .NET
the original type in the class and convert it to bytes. Then transfer the bytes to the FileStream
class.
Program then creates a BinaryReader
target for the FileStream
read data. Before using BinaryReader
, you must first return to the beginning of the file, that is, call Seek()
the method FileStream
to relocate, and then read the data from the file.
3. Use File's binary function
.NET Framework
A special File class is provided to handle file-related functions. It File
is a tool class and a static
class. Just use " File.方法
" directly .
Among these methods, one is to get a stream for convenient operation, such as File.Create(path)
creating or opening one FileStream
, and File.OpenRead(path)
get one FileStream
for reading and File.OpenWrite(path)
one FileStream
for writing.
The other type is more convenient. There is only one way to open, read and write, and close files, including:
- ①
File. ReadAlIBytes(path)
Read all the bytes of a file, and return a byte array; - ②Write the
File. WriteAllBytes(path,bytes)
byte array to a file; - ③
File. Copy(path,path2)
Copy files.
Serialization and deserialization
1. What is object serialization
C# objects are generally located in memory, but in real applications, it is often required to save (persistent) the specified object after the C# program stops running, and to re-read the saved object in the future. C# object serialization (serialize), deserialize (deserialize) can achieve this function.
Using object serialization, when the object is saved to disk or output to the network, its state will be saved as a set of bytes, and these bytes will be converted into objects in the future (deserialization). In addition to object serialization when persisting objects, object serialization is also used when remote method calls (such as Remoting
, WebService
etc.) are used or objects are transferred over the network. In addition, you can also serialize and deserialize an object to get a copy of the object.
2. Simple serialization and deserialization
System.Runtime.Serialization
The namespace provides object serialization and serialization functions. As long as a class is marked with [Serializable]
this feature ( Attribute
), then it can be serialized. To perform serialization and deserialization operations, you need an implemented IFormatter
object IFormatter
with Serialize(stream, object)
and Deserialize(stream)
methods. .NET Framework
The following IFormatter objects have been implemented in.
- ①
BinaryFormatter
, Binary format, can serialize objects into binary information, mainly used for object state preservation (such as game state), remote call (Remoting), it is characterized by high efficiency, but can only be.NET Framework
deserialized in the platform . This requiresSystem.Runtime.Serialization.Formatters.Binary
namespaces. - ②
XMLDeserialize
XML formatting can serialize objects into standardized XML information, which is mainly used for object state preservation and data exchange. Its characteristic is that it can exchange data with languages on other platforms. It should be noted that here is not usedIFormatter
, butSystem.XML.Serialization
theXmlSerializer
class in the namespace , which also hasSerialize()
andDeserialize()
methods. - ③ SoapFormatter, SOAP is a format of XML Web Service remote service call, mainly used for XML Web Service, there are special tools in Visual Studio to automatically process.
Example, serialization in binary and XML format:
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;
[Serializable]
public class Person
{
public string Name {
get; set; }
public int Age {
get; set; }
public Person() {
}
public Person(string name, int age) {
this.Name = name;
this.Age = age;
}
public override string ToString() {
return Name + "(" + Age + ")";
}
}
public class SerializeDemo
{
public static void TestMain() {
Person[] people = {
new Person("李明", 18),
new Person("王强", 19),
};
// 二进制序列化
BinaryFormatter binary = new BinaryFormatter();
string fileName = "s.temp";
BinarySerialize(binary, fileName, people);
// 二进制反序列化
Person[] people1 = BinaryDeserialize(binary, fileName) as Person[];
foreach (Person p in people1)
Console.WriteLine(p);
// XML序列化
XmlSerializer xmlser = new XmlSerializer(typeof(Person[]));
string xmlFileName = "s.xml";
XmlSerializer(xmlser, xmlFileName, people);
// 显示XML文本
string xml = File.ReadAllText(xmlFileName);
Console.WriteLine(xml);
}
private static void BinarySerialize(IFormatter formatter, string fileName, object obj) {
FileStream fs = new FileStream(fileName, FileMode.Create);
formatter.Serialize(fs, obj);
fs.Close();
}
private static object BinaryDeserialize(IFormatter formatter, string fileName) {
FileStream fs = new FileStream(fileName, FileMode.Open);
object obj = formatter.Deserialize(fs);
fs.Close();
return obj;
}
private static void XmlSerializer(XmlSerializer ser, string fileName, object obj) {
FileStream fs = new FileStream(fileName, FileMode.Create);
ser.Serialize(fs, obj);
fs.Close();
}
}
operation result:
李明(18)
王强(19)
<?xml version="1.0"?>
<ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Person>
<Name>李明</Name>
<Age>18</Age>
</Person>
<Person>
<Name>王强</Name>
<Age>19</Age>
</Person>
</ArrayOfPerson>