1. BinaryReader 클래스 및 BinaryWriter 클래스
BinaryReader
그리고, BinaryWriter
(예컨대 기본 데이터 타입의 읽고 쓰기, 2 진 입력 / 출력을 위해 사용될 수있다 int
, double
등) 대신에 원래 바이트 타입. BinaryReader
그리고 BinaryWriter
없는 Stream
클래스의 서브 클래스, 그러나 그것은이다 Stream
구성의 흐름 포장, BinaryReader
및 BinaryWriter
객체, 필요한 Stream
인수로 객체입니다. 예 :
new BinaryReader(myStream);
실제로이 두 유형은 주로 기본 유형과 원시 바이트간에 변환되므로 Stream
FileStream 또는 .NET과 같은 bytes 에서 I / O를 수행 할 수있는 몇 가지 기본 객체 를 처리해야합니다 MemoryStream
. 두 유형 모두 BaseStream
기본 Stream
개체에 대한 참조 를 얻을 수 있는 속성을 가지고 있습니다 . 다음은 BinaryWriter
몇 가지 방법 의 클래스 :
BinaryReader
와 BinaryWriter
매우 유사한 기능, 여러가 ReadXXX()
방법 다른 이름 . 예를 들어, 메서드와 메서드 BinaryWriter
가있을 수 있지만 zhong 에는 메서드와 메서드 만 있습니다 . 쓰기 작업을 수행 할 때 writer 객체는 Write ()의 매개 변수를 기반으로 쓰여진 내용을 추론 할 수 있기 때문입니다. 읽기 작업을 수행 할 때 각 바이트 스트림에 대해 판독기 객체는 이러한 바이트를 처리하는 방법을 모릅니다. 함께 구성됩니다. 독자 객체에 바이트 스트림을 함께 구성하는 방법을 알려줄 수 있도록 특정 함수를 호출해야합니다.Write(Int16)
Write(Char)
BinaryReader
ReadInt16()
ReadChar()
2. 스트림을 사용한 바이너리 입 / 출력
BinaryReader
그리고 BinaryWriter
가능 Stream
입력 / 출력 원시 이진 데이터로 포장 될 수있다.
예를 들어 이진 형식으로 파일에 데이터를 쓴 다음 파일에서 데이터를 읽습니다.
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());
}
}
}
이 예에서는 FileStream
파일에서 작동 하도록 개체 가 만들어 집니다. 객체를 생성 할 때 두 번째 매개 변수는 파일을 여는 방법을 결정합니다.이 예에서는 FileMode.Create
새 파일을 만들거나 같은 이름의 기존 파일을 덮어 쓰는 것을 의미합니다. 세 번째 매개 변수는이 예에서 사용 된 파일의 FileAccess.ReadWrite
읽기 및 쓰기 권한을 결정 합니다.
FileStream
일반적으로 불편한 작업을 직접 수행 할 수 있으므로 FileStream
종종 바이트를 변환 할 수있는 다른 클래스로 패키지화됩니다. 위와 같이 BinaryWriter
클래스 .NET
에서 원래 유형을 수신 하여 바이트로 변환 할 수 있는 클래스가 사용 됩니다. 그런 다음 바이트를 FileStream
클래스 로 전송하십시오 .
그런 다음 프로그램 BinaryReader
은 FileStream
읽은 데이터에 대한 대상 을 만듭니다 . 를 사용하기 전에 BinaryReader
먼저 파일의 시작 부분으로 돌아 가야합니다. 즉, 재배치 Seek()
할 메서드 FileStream
를 호출 한 다음 파일에서 데이터를 읽어야합니다.
3. 파일의 바이너리 함수 사용
.NET Framework
파일 관련 기능을 처리하기위한 특별한 File 클래스가 제공되며 File
도구 클래스이자 static
클래스로 " File.方法
"를 직접 사용하면됩니다 .
이 중 하나는 File.Create(path)
생성 또는 열기 와 같은 편리한 작업을 위해 스트림을 가져 FileStream
오고, File.OpenRead(path)
하나 FileStream
는 읽기 용으로, File.OpenWrite(path)
다른 하나 FileStream
는 쓰기 용으로 가져 오는 것 입니다 .
다른 유형이 더 편리합니다. 다음을 포함하여 파일을 열고, 읽고, 쓰고, 닫는 한 가지 방법 만 있습니다.
- ①
File. ReadAlIBytes(path)
파일의 모든 바이트를 읽고 바이트 배열을 반환합니다. - ②
File. WriteAllBytes(path,bytes)
바이트 배열을 파일에 씁니다. - ③
File. Copy(path,path2)
파일을 복사합니다.
직렬화 및 역 직렬화
1. 객체 직렬화 란?
C # 개체는 일반적으로 메모리에 있지만 실제 응용 프로그램에서는 C # 프로그램 실행이 중지 된 후 지정된 개체를 저장 (영구)하고 나중에 저장된 개체를 다시 읽어야하는 경우가 많습니다. C # 개체 직렬화 (직렬화), 역 직렬화 (역 직렬화)는이 기능을 수행 할 수 있습니다.
개체 직렬화를 사용하면 개체가 디스크에 저장되거나 네트워크에 출력 될 때 해당 상태가 바이트 집합으로 저장되고 이러한 바이트는 나중에 개체로 변환됩니다 (역 직렬화). 원격 메소드 호출 (예 때 객체 직렬화 외에 오브젝트를 지속에서 객체 직렬화도 사용된다 Remoting
, WebService
등)에 사용되는 개체 또는 네트워크를 통해 전송된다. 또한 개체를 직렬화 및 역 직렬화하여 개체의 복사본을 가져올 수도 있습니다.
2. 간단한 직렬화 및 역 직렬화
System.Runtime.Serialization
네임 스페이스는 개체 직렬화 및 직렬화 기능을 제공합니다. 클래스 [Serializable]
가이 기능 ( Attribute
)으로 표시되어 있으면 직렬화 할 수 있습니다. 직렬화 및 역 직렬화 작업을 수행하려면 및 메서드를 사용 하여 구현 된 IFormatter
개체 IFormatter
가 필요합니다 . 다음 IFormatter 개체가 구현되었습니다.Serialize(stream, object)
Deserialize(stream)
.NET Framework
- ①
BinaryFormatter
Binary 형식은 주로 개체 상태 보존 (예 : 게임 상태), 원격 호출 (Remoting)에 사용되는 이진 정보로 개체를 직렬화 할 수 있으며 높은 효율성이 특징이지만.NET Framework
플랫폼 에서만 역 직렬화 할 수 있습니다 . 여기에는System.Runtime.Serialization.Formatters.Binary
네임 스페이스 가 필요 합니다. - ②
XMLDeserialize
XML 포맷팅은 객체를 표준화 된 XML 정보로 직렬화 할 수 있으며, 주로 객체 상태 보존 및 데이터 교환에 사용되며 다른 플랫폼의 언어와 데이터를 교환 할 수있는 것이 특징입니다. 여기서는 사용되지IFormatter
않지만 및 메서드 가System.XML.Serialization
있는 네임 스페이스의XmlSerializer
클래스 입니다 .Serialize()
Deserialize()
- ③ SoapFormatter, SOAP는 XML Web Service 원격 서비스 호출 형식으로 주로 XML Web Service에 사용되며 Visual Studio에는 자동으로 처리하는 특수 도구가 있습니다.
예, 바이너리 및 XML 형식의 직렬화 :
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();
}
}
작업 결과 :
李明(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>