C#/기초
C#에서 SOAP 방식으로 구조체를 직렬화(Serialization)하는 예제 소스
떡잎
2012. 12. 12. 19:01
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Soap;
namespace SerializationSoapStruct
{
// 대괄호가 붙으면 attribute
[Serializable] // 직렬화
struct Person
{
public string name;
public int age;
[NonSerialized] // 직렬화하지 않은 변수
public string hobby;
}
class Program
{
static void Main(string[] args)
{
Person personOut = new Person();
personOut.name = "최말봉";
personOut.age = 40;
personOut.hobby = "인터넷";
// 직렬화
FileStream fsOut = new FileStream("sss.xml", FileMode.Create);
SoapFormatter soapOut = new SoapFormatter();
Console.WriteLine("직렬화");
Console.WriteLine("--------------------");
soapOut.Serialize(fsOut, personOut);
fsOut.Close();
Console.WriteLine(personOut.name);
Console.WriteLine(personOut.age);
Console.WriteLine(personOut.hobby);
Console.WriteLine();
Console.WriteLine("====================");
Console.WriteLine();
// 역직렬화
FileStream fsIn = new FileStream("sss.xml", FileMode.Open);
SoapFormatter soapIn = new SoapFormatter();
Console.WriteLine("역직렬화");
Console.WriteLine("--------------------");
Person personIn = (Person)soapIn.Deserialize(fsIn);
fsIn.Close();
Console.WriteLine(personIn.name);
Console.WriteLine(personIn.age);
Console.WriteLine(personIn.hobby);
Console.ReadLine();
}
}
}
NonSerialized로 어트리뷰트를 준것은 역직렬화에서 출력했을 때 데이터를 가져오지 않는다.
System.Runtime.Serialization.Formatters.Soap는 참조에서 추가해야된다.
참조에 대한 추가 방법은 아래 링크 참고
C#에서 SOAP 방식 직렬화(Serialization) 예제 소스