C# study notes binary input and output

1.BinaryReader class and BinaryWriter class

BinaryReaderAnd BinaryWritercan be used for binary input/output, that is, to read and write basic data types (such as int, doubleetc.) instead of the original byte types. BinaryReaderAnd BinaryWriteris not a Streamsubclass of the class, but it is a Streamflow packaging, in the configuration BinaryReader, and BinaryWriteran object, a required Streamobject 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 Streamobjects that can perform I/O on bytes , such as FileStream or MemoryStream. Both types have an BaseStreamattribute through which Streama reference to the basic object can be obtained . The following are BinaryWritersome methods of the class:
Insert picture description here
BinaryReaderwith BinaryWritervery similar functions, there are multiple ReadXXX()methods with different names . For example, BinaryWriterthere can be Write(Int16)methods and Write(Char)methods in, but BinaryReaderonly 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

BinaryReaderAnd BinaryWritercan Streambe 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 FileStreamobject 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.
FileStreamYou can perform operations on your own, which is usually inconvenient, so it is FileStreamoften packaged into other classes that can convert bytes. As above, a BinaryWriterclass is used that can receive .NETthe original type in the class and convert it to bytes. Then transfer the bytes to the FileStreamclass.
Program then creates a BinaryReadertarget for the FileStreamread data. Before using BinaryReader, you must first return to the beginning of the file, that is, call Seek()the method FileStreamto relocate, and then read the data from the file.

3. Use File's binary function

.NET FrameworkA special File class is provided to handle file-related functions. It Fileis a tool class and a staticclass. 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 FileStreamfor reading and File.OpenWrite(path)one FileStreamfor 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, WebServiceetc.) 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.SerializationThe 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 IFormatterobject IFormatterwith Serialize(stream, object)and Deserialize(stream)methods. .NET FrameworkThe 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 Frameworkdeserialized in the platform . This requires System.Runtime.Serialization.Formatters.Binarynamespaces.
  • XMLDeserializeXML 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 used IFormatter, but System.XML.Serializationthe XmlSerializerclass in the namespace , which also has Serialize()and Deserialize()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>

Guess you like

Origin blog.csdn.net/qq_45349225/article/details/114401197