간단한 방법

//Class Save
   Class1 c1 = new Class1("kojaedoo");
   BinaryFormatter serializer = new BinaryFormatter();  
   Stream stream = File.Open("data.txt", FileMode.Create);
   serializer.Serialize(stream ,c1);   
   stream.Close();
   c1 = null;

   //Class Open
   stream = File.Open( "data.txt", FileMode.Open  );
   BinaryFormatter formatter = new BinaryFormatter();

   Class1 c3 = (Class1)formatter.Deserialize( stream );
   MessageBox.Show( "클래스에서 가지고 온값::::"+c3.GetName());

 

 

MSDN Home >  Visual Studio .NET >  Visual Basic 및 Visual C# >  구성 요소를 사용한 프로그래밍 >  구성 요소 제작 >  구성 요소에서 속성, 메서드, 멤버 및 이벤트의 구현 
Visual Basic 및 Visual C# 개념  

구성 요소의 속성 저장


가끔 구성 요소의 상태를 저장해야 하는 경우가 있습니다. 이러한 경우에는 예를 들어, 구성 요소의 사용자에 대한 개별 정보를 저장하거나 사용자 지정 컨트롤의 기본 구성을 변경합니다.

serialization이라는 과정을 통해 구성 요소의 상태를 파일에 저장할 수 있습니다. serialize하면 개체를 데이터 스트림으로 변환한 다음 파일에 저장할 수 있습니다. 또한 스트림은 다시 deserialization을 통해 개체로 변환될 수 있습니다.

.NET Framework는 serialization을 위해 다음과 같은 두 가지 포맷터, 즉 BinaryFormatter 클래스 및 SOAPFormatter 클래스를 제공합니다. 이 클래스는 현재 메모리에 있는 개체의 내부 메모리를 표현한 개체 그래프를 사용하여 데이터 스트림으로 변환합니다. 각 포맷터의 기능은 이름에 잘 나타나 있습니다. BinaryFormatter는 개체 그래프를 데스크톱 응용 프로그램에서 가장 유용하게 사용되는 이진 스트림으로 변환하고 SOAPFormatter는 개체 그래프를 인터넷 응용 프로그램에서 가장 유용하게 사용되는 SOAP(Simple Object Access Protocol) 형식으로 변환합니다. 그러면 이 스트림은 deserialize될 수 있는 파일로 저장될 수 있고 필요하면 다시 개체로 변환될 수 있습니다.

스트림 Serialization
구성 요소의 상태를 저장하려면

SerializableAttribute 특성을 serialize할 구성 요소에 적용합니다.
' Visual Basic
<Serializable()> Public Class Account
   ' Insert code to implement class.
End Class

// C#
[Serializable()]
public class Account
{
   // ' Insert code to implement class.
}
이 클래스의 인스턴스를 저장할 개체로 만듭니다.
' Visual Basic
Dim myAccount As New Account()

// C#
Account myAccount = new Account();
Stream 개체를 serialize된 데이터에 리포지토리를 제공하는 파일로 만듭니다.
' Visual Basic
Imports System.IO
' This creates a new file with the name SavedAccount.txt, and creates
' a Stream object to write data to that file. The GetFolderPath method
' is used to get the path to the current user's Personal folder.
Dim myFileStream As Stream = File.Create _
   (System.Environment.GetFolderPath _
      (System.Environment.SpecialFolder.Personal))

// C#
using System.IO;
// This creates a new file with the name SavedAccount.txt, and creates
// a Stream object to write data to that file. The GetFolderPath method
// is used to get the path to the current user's Personal folder.
Stream myFileStream = File.Create
   (System.Environment.GetFolderPath
      (System.Environment.SpecialFolder.Personal));
포맷터 클래스의 인스턴스를 만듭니다.
개체 그래프를 이진 스트림으로 변환하려면 BinaryFormatter 클래스의 인스턴스를 만듭니다.
' Visual Basic
Imports System.Runtime.Serialization.Formatters.Binary
Dim serializer As New BinaryFormatter()

// C#
using System.Runtime.Serialization.Formatters.Binary;
BinaryFormatter serializer = new BinaryFormatter();
개체 그래프를 SOAP 스트림으로 변환하려면 SoapFormatter 클래스의 인스턴스를 만듭니다.
참고   프로젝트에 System.Runtime.Serialization.Formatters.Soap 네임스페이스에 대한 참조가 있어야 합니다.
' Visual Basic
Imports System.Runtime.Serialization.Formatters.Soap
Dim serializer as New SoapFormatter

// C#
using System.Runtime.Serialization.Formatters.Soap;
SoapFormatter serializer = new SoapFormatter();
포맷터의 Serialize 메서드를 호출하여 개체를 Stream에 씁니다.
' Visual Basic
serializer.Serialize(myFileStream, myAccount)
myFileStream.Close()

// C#
serializer.Serialize(myFileStream, myAccount);
myFileStream.Close();
파일 스트림을 닫고 serialization을 완료합니다.
이제 SavedAccount.txt 파일에 개체의 인스턴스가 이진 형식으로 저장되었습니다.

스트림 Deserialization
개체를 저장한 다음 나중에 검색할 수 있습니다. 구성 요소를 serialize할 때 사용한 것과 동일한 포맷터를 deserialization에 사용할 수 있습니다.

저장된 구성 요소를 복원하려면

복원할 클래스와 동일한 형식의 변수를 선언합니다.
' Visual Basic
Dim restoredAccount As Account

// C#
Account restoredAccount;
Stream 개체를 만들고 serialize된 개체가 있는 파일을 엽니다.
' Visual Basic
Imports System.IO
Dim myFileStream As Stream = File.OpenRead _
   (System.Environment.GetFolderPath _
      (System.Environment.SpecialFolder.Personal))

// C#
using System.IO;
Stream myFileStream = File.OpenRead
   (System.Environment.GetFolderPath
      (System.Environment.SpecialFolder.Personal));
데이터를 serialize하는 데 사용한 것과 동일한 형식으로 포맷터 클래스의 인스턴스를 만듭니다.
다음 예제에서는 BinaryFormatter 클래스를 사용하는 방법을 보여 줍니다.
' Visual Basic
Imports System.Runtime.Serialization.Formatters.Binary
Dim deserializer As New BinaryFormatter()

// C#
using System.Runtime.Serialization.Formatters.Binary;
BinaryFormatter deserializer = new BinaryFormatter();
다음 예제에서는 SoapFormatter 클래스를 사용하는 방법을 보여 줍니다.
참고   프로젝트에 System.Runtime.Serialization.Formatters.Soap 네임스페이스에 대한 참조가 있어야 합니다.
' Visual Basic
Imports System.Runtime.Serialization.Formatters.Soap
Dim deserializer As New SoapFormatter()

// C#
using System.Runtime.Serialization.Formatters.Soap;
SoapFormatter deserializer = new SoapFormatter();
파일 스트림을 개체 그래프로 변환하려면 포맷터의 Deserialize 메서드를 호출하고 개체 그래프를 원하는 형식의 개체로 변환하려면 CType 함수(Visual Basic) 또는 명시적 캐스트(C#)를 사용합니다.
' Visual Basic
' The CType function converts the file stream specified in the first
' argument to an object of the type specified in the second argument.
' If the object in the first argument cannot be converted to the
' specified type, an error will result.
restoredAccount = CType(deserializer.Deserialize(myFileStream), _
   Account)
myFileStream.Close()

// C#
// The explicit cast converts the file stream to an object of the type // specified. If the object in the file stream cannot be converted to // the specified type, an error will result.
restoredAccount = (Account)(deserializer.Deserialize(myFileStream));
myFileStream.Close();
보안 정보   이 기술은 데이터 보안에 적합하지 않으므로 중요하거나 기밀을 요하는 데이터를 저장하는 데는 이 기술을 사용하지 마십시오. 데이터의 보안 암호화 스키마를 만드는 방법에 대한 자세한 내용은 System.Security.Cryptography 네임스페이스를 참조하십시오.
참고 항목
BinaryFormatter 클래스 | SOAPFormatter 클래스 | SerializableAttribute 클래스 | System.Security.Cryptography 네임스페이스 | 구성 요소 제작

http://msdn.microsoft.com/library/KOR/vbcon/html/vbtsksavingpropertiesofyourcontrol.asp?frame=true

+ Recent posts