반응형

* C# 파일 예제

 

메인 화면

Form1.cs

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;

namespace CSharp_FileEx
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            string strCheckFolder = "";

            //TEST 폴더 만들기...
            strCheckFolder = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf('\\'));
            strCheckFolder += "\\TEST";
            if (!System.IO.Directory.Exists(strCheckFolder))
            {
                System.IO.Directory.CreateDirectory(strCheckFolder);

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Create
            try
            {
                string strCheckFolder = "";

                strCheckFolder = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf('\\'));
                strCheckFolder += "\\TEST\\TEST.txt";
                
                if (!System.IO.File.Exists(strCheckFolder))
                {
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(strCheckFolder, true, Encoding.GetEncoding(949)))
                    {
                        sw.Write("\r\n");
                        sw.Flush();
                        sw.Close();
                    }

                }

                FileInfo fi = new FileInfo(strCheckFolder);

                lblCreate.Text = "*Message: " + fi.Name + " 파일을 만들었습니다.";
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                
            }
            
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //Delete
            string strCheckFolder = "";

            strCheckFolder = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf('\\'));
            strCheckFolder += "\\TEST\\TEST.txt";

            //파일이 있다면...
            if (File.Exists(strCheckFolder))
            {
                FileInfo fi = new FileInfo(strCheckFolder);

                lblDelete.Text = "*Message: " + fi.Name + " 파일을 삭제 했습니다.";
                File.Delete(strCheckFolder);
                
            }
            else
            {
                lblDelete.Text = "해당 파일이 없습니다.";
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            //Read
            string strCheckFolder = "";

            strCheckFolder = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf('\\'));
            strCheckFolder += "\\TEST\\TEST.ZerosKD";

            if (!File.Exists(strCheckFolder))
            {
                lblRead.Text = "해당 파일이 없습니다. File Read Fail.";
                return;
            }

          
            string[] strValue = File.ReadAllLines(strCheckFolder);

            for (int iCount = 0; iCount < strValue.Length; iCount++)
            {
                txtRead.Text += strValue[iCount] + System.Environment.NewLine ;
            }
            txtRead.Text += "File Read TEST" + "\r\n";
            FileInfo fi = new FileInfo(strCheckFolder);
            lblRead.Text = fi.Name + " File Read Complete.";

        }

        private void button3_Click(object sender, EventArgs e)
        {
            //Write
            try
            {
                string strCheckFolder = "";
                
                strCheckFolder = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf('\\'));
                strCheckFolder += "\\TEST\\TEST.ZerosKD";

                //True : Append 기존 파일이 있을 경우 추가해서 쓴다. False : 기존 파일이 있을 경우 덮어쓴다.
                using (StreamWriter sw = new StreamWriter(strCheckFolder, true))
                {
                    sw.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " => " + "File 예제..." + "\r\n");
                    sw.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " => " + txtWrite.Text  + "\r\n");
                    sw.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " => " + "============" + "\r\n");
                    sw.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " => " + "File Write TEST" + "\r\n");
                    sw.Flush();
                    sw.Close();
                }

                FileInfo fi = new FileInfo(strCheckFolder);
                lblWriteFile.Text = fi.Name + " File Write Complete.";

            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message.ToString());
                
            }
        }
    }
}

 

위 소스에서 보시는 거와 같이 파일 저장 시 확장자 명은 사용자가 정의 해서 사용 할 수 있습니다.

 

결과 화면

 

반응형
반응형

* INI 파일 예제...

 

예제 메인화면

 

Form1.cs

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Runtime.InteropServices;


namespace CSharp_INIFile
{
    public partial class Form1 : Form
    {
        #region INI 파일 사용을 위해 API 선언...

        [DllImport("KERNEL32.DLL")]
        private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);

        [DllImport("KERNEL32.DLL")]
        private static extern uint GetPrivateProfileInt(string lpAppName, string lpKeyName, int nDefault, string lpFileName);

        [DllImport("kernel32.dll")]
        static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName);

        #endregion

        #region 정의 함수...
        //INIFile 읽어오기...
        private string getIni(string IpAppName, string IpKeyName, string lpDefalut, string filePath)
        {
            string inifile = filePath;    //Path + File

            try
            {
                StringBuilder result = new StringBuilder(255);
                GetPrivateProfileString(IpAppName, IpKeyName, lpDefalut, result, result.Capacity , inifile);

                return result.ToString();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return "실패";
            }
        }

        //INIFile 쓰기...
        private Boolean setIni(string IpAppName, string IpKeyName, string IpValue, string filePath)
        {
            try
            {
                string inifile = filePath;  //Path + File
                WritePrivateProfileString(IpAppName, IpKeyName, IpValue, inifile);
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return false;
            }
        }

        //INIFile 만들기...
        private Boolean CreateIni(string strFileName)
        {
            try
            {
                string strCheckFolder = "";

                strCheckFolder = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf('\\'));
                strCheckFolder += "\\INI";
                if (!System.IO.Directory.Exists(strCheckFolder))
                {
                    System.IO.Directory.CreateDirectory(strCheckFolder);

                }

                strCheckFolder += "\\" + strFileName + ".ini";
                if (!System.IO.File.Exists(strCheckFolder))
                {
                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(strCheckFolder, true, Encoding.GetEncoding(949)))
                    {
                        sw.Write("\r\n");
                        sw.Flush();
                        sw.Close();
                    }

                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                return false;
            }
            return true;
        }


        #endregion

        string strCheckFolder = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf('\\'));

        public Form1()
        {
            InitializeComponent();

            strCheckFolder += "\\INI";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //만들기...
            if (CreateIni("Test"))
            {
                label1.Text = "INIFile Create Complete.";
                label2.Text = "FileName: Test.ini";
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //읽기...
            label4.Text = "INIFile Read Complete.";
            label3.Text = getIni("Test_Info", "Test", "", strCheckFolder + "\\Test.ini");

        }

        private void button3_Click(object sender, EventArgs e)
        {
            //쓰기...
            if (setIni("Test_Info", "Test", "1231231231", strCheckFolder + "\\Test.ini"))
            {
                label6.Text = "INIFile Write Complete.";
                label5.Text = "Value: 1231231231";
            }
        }
    }

    

}

 

위 예제는 윈도우 API 함수를 이용해 INI 파일을 읽고 쓰기를 해 보았습니다. INI 파일 삭제는

if ( File.Exits("파일위치")) File.Delete("파일위치") ; 파일 삭제랑 똑같기 때문에 따로 넣진 않았습니다.

 

* 예제 결과

 

결과 화면

위 사진은 INI 파일 내용 으로 INI File Read 시 어떤 내용을 읽어 오는지를 참조 하기 위해...

반응형
반응형

* 윈도우 레지스트리에 읽고 쓰고 만들고 지우기 예제

 

메인 화면

 

Form1.vb

 

Imports Microsoft.Win32

Public Class Form1

    Dim strAppName As String = "RegistryTest"

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        '쓰기
        WriteRegistry(strAppName, "Test1", "iii", "asdfasdf000")
        WriteRegistry(strAppName, "Test2", "iii", "asdfasdf111")
        WriteRegistry(strAppName, "Test3", "iii", "asdfasdf222")
        WriteRegistry(strAppName, "Test4", "iii", "asdfasdf333")

        '읽기
        'MessageBox.Show(ReadRegistry(strAppName,"Test1","iii"))

        '삭제
        'DeleteReg(strAppName)

        '등록된 목록 읽기
        Dim rk As RegistryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\" + strAppName)
        Dim str() As String = rk.GetSubKeyNames()

        For iCount As Integer = 0 To str.Length - 1
            ListBox1.Items.Add(str(iCount))
        Next

    End Sub

    '레지스트리도 폴더 개념으로 접근...
#Region " RegisTry Create & Read & Write & Delete..."

    Private Function DeleteReg(ByVal strSubKey As String) As Boolean
        Dim rk As RegistryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\", True)
        Try
            '하위 폴더(레지스트리)가 있으면 삭제 안됨.
            'if(Not rk Is Nothing) Then rkDeleteSubKey(strSubKey)

            '하위 폴더(레지스트리) 가 있던 없던 걍 삭제...
            If Not rk Is Nothing Then
                rk.DeleteSubKeyTree(strSubKey)
            End If
        Catch ex As Exception
            Return False
        End Try
        Return True
    End Function

    '레지스트리 쓰기
    Private Function WriteRegistry(ByVal strAppName As String, ByVal strSubKey As String, ByVal strKey As String, ByVal strValue As String) As Boolean

        Dim rkReg As RegistryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\" + strAppName, True)
        'null 이면 폴더(레지스트리)가 없으므로 만듬...
        If rkReg Is Nothing Then
            rkReg = Registry.CurrentUser.CreateSubKey("SOFTWARE\" + strAppName)
        End If

        'OpenSubKey (하위폴더(레지스트리 이름) , 쓰기 선택 True 쓰기 False 및 인자가 없다면 읽기)
        Dim rkSub As RegistryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\" + strAppName + "\\" + strSubKey, True)
        If rkSub Is Nothing Then
            rkSub = Registry.CurrentUser.CreateSubKey("SOFTWARE\" + strAppName + "\\" + strSubKey)
        End If

        Try
            rkSub.SetValue(strKey, strValue)
        Catch ex As Exception
            Console.WriteLine(ex.Message.ToString())
            Return False
        End Try
        Return True
    End Function
    '레지스트리 읽기
    Private Function ReadRegistry(ByVal strAppName As String, ByVal strSubKey As String, ByVal strKey As String) As String
        Dim reg As RegistryKey

        Try
            reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\" + strAppName).OpenSubKey(strSubKey)
        Catch ex As Exception
            Return ""
        End Try

        Return reg.GetValue(strKey, "").ToString()
    End Function

#End Region

    
End Class

 

 

아래의 그림을 보면

HKEY_CUREENT_USER 가 트리뷰에서 보이게 됩니다.

 Registry.CurrentUser 는 저 레지스트리 폴더를 가르키게 되며

Registry.LocalMachine는 그 아래에 있는 HKEY_LOCAL_MACHINE 으로 들어가게 됩니다.

 

위 소스 Registry.CurrentUer.OpenSubKey("SOFTWARE") 는

레지스트리에 HKEY_CURRENT_USER => Software 폴더를 열겠다는 뜻

 

*레지스트리 편집기 (시작 -> 실행 -> regedit)

  

레지스트리 편집기 실행 

 

레지스트리 프로그램 실행 후 편집기 실행

Imports Microsoft.Win32

레지스트리 클래스를 사용하기 위해선 Microsoft.Win32 를 임포트 시켜 줘야 함.

반응형
반응형

* 윈도우 레지스트리에 읽고 쓰고 만들고 지우기 예제

레지스트리 메인화면

Form1.cs

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using Microsoft.Win32;

namespace CSharp_Resistry
{
    public partial class Form1 : Form
    {
        string strTmp = "SOFTWARE\\"; //레지스트리 최상위 폴더 지정
        string strAppName = "RegistryTest";


        public Form1()
        {
            InitializeComponent();

            //쓰기
            WriteReg(strAppName, "Test1", "iii", "asdfasdf000");
            WriteReg(strAppName, "Test2", "iii", "asdfasdf111");
            WriteReg(strAppName, "Test3", "iii", "asdfasdf222");
            WriteReg(strAppName, "Test4", "iii", "asdfasdf333");

            //읽기
            //MessageBox.Show(ReadReg(strAppName,"Test1","iii"));

            //삭제
            //DeleteReg(strAppName);


            //등록된 목록 읽기
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(strTmp + strAppName);
            string[] str = rk.GetSubKeyNames();

            for (int iCount = 0; iCount < str.Length; iCount++)
            {
                lbList.Items.Add(str[iCount]);
            }


        }

        //레지스트리도 폴더 개념으로 접근...
        #region Registry Create & Read & Write & Delete...
        
        private bool DeleteReg(string strSubKey)
        {
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(strTmp, true);
            try
            {
                //하위 폴더(레지스트리)가 있으면 삭제 안됨.
                //if(rk !=null) rkDeleteSubKey(strSubKey);

                //하위 폴더(레지스트리) 가 있던 없던 걍 삭제...
                if (rk != null) rk.DeleteSubKeyTree(strSubKey);
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        //레지스트리 쓰기
        private   bool WriteReg(string strAppName,
                                    string strSubKey,
                                    string strKey,
                                    string strValue)
        {

            RegistryKey rkReg = Registry.CurrentUser.OpenSubKey(strTmp + strAppName, true);
            //null 이면 폴더(레지스트리)가 없으므로 만듬...
            if (rkReg == null) rkReg = Registry.CurrentUser.CreateSubKey(strTmp  + strAppName);
            
            //OpenSubKey (하위폴더(레지스트리 이름) , 쓰기 선택 True 쓰기 False 및 인자가 없다면 읽기)
            RegistryKey rkSub = Registry.CurrentUser.OpenSubKey(strTmp + strAppName + "\\" + strSubKey, true);
            if (rkSub == null) rkSub = Registry.CurrentUser.CreateSubKey(strTmp + strAppName + "\\" + strSubKey);

            try
            {
                rkSub.SetValue(strKey, strValue);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                return false;
            }
            return true;
        }
        //레지스트리 읽기
        private string ReadReg(string strAppName,
                                    string strSubKey,
                                    string strKey)
        {
            RegistryKey reg;
           
            try
            {
                reg = Registry.CurrentUser.OpenSubKey(strTmp + strAppName ).OpenSubKey(strSubKey);
            }
            catch (Exception ex)
            {
                return "";
            }
          
            return reg.GetValue(strKey, "").ToString();
        }

        #endregion

    }
}

 

아래의 그림을 보면 

HKEY_CUREENT_USER 가 트리뷰에서 보이게 됩니다.

Registry.CurrentUser 는 저 레지스트리 폴더를 가르키게 되며

Registry.LocalMachine는 그 아래에 있는 HKEY_LOCAL_MACHINE 으로 들어가게 됩니다.

 

위 소스 Registry.CurrentUer.OpenSubKey("SOFTWARE") 는

레지스트리에 HKEY_CURRENT_USER => Software 폴더를 열겠다는 뜻

 

*레지스트리 편집기 (시작 -> 실행 -> regedit)

  

레지스트리 편집기 실행 
레지스트리 프로그램 실행 후 편집기 실행

 

반응형
반응형

* C# 소스코드를 동적으로 컴파일 하는 예제

 

기본 메인화면

Form1.cs

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.CodeDom.Compiler;
using System.Runtime.InteropServices;

namespace CSharp_동적컴파일
{
    public partial class Form1 : Form
    {
        //API 선언 (다른 프로그램 실행 시키키 위한 변수)
        [DllImport("Shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd);

        public Form1()
        {
            InitializeComponent();

            textBox1.Text = @"using System;

                                namespace Zmeun.CodeDom
                                {
                                    class CodeDomTest
                                    {
                                        static void Main(string[] args)
                                        {
                                            System.Console.WriteLine(""Hello World!"");
                                            System.Console.WriteLine(""Press the Enter key to continue."");
                                            System.Console.ReadLine();
                                        }
                                    }
                                }";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("c#");
            CompilerParameters compilerParameters = new CompilerParameters();

            //.GenerateExecutable 이값을 'false'로 하면 dll로 출력됨
            compilerParameters.GenerateExecutable = true;
            //컴파일 된 EXE 파일 출력 Path
            compilerParameters.OutputAssembly = @"c:\test.exe";
            CompilerResults compilerResults = codeDomProvider.CompileAssemblyFromSource(compilerParameters, textBox1.Text );

            if (compilerResults.Errors.Count > 0)
            {
                textBox1.Text = compilerResults.Errors[0].ToString();
            }
            else
            {
                textBox1.Text = "성공";
            }
            
            //컴파일된 프로그램 실행 시키기...
            ShellExecute(this.Handle, "open", "C:\\test.exe", "", "", 4);

        }
    }
}

 

실행 결과

 

 

반응형
반응형

* 객체 직렬화 (Serialization)

 - 객체를 메모리나 파일, 데이터 베이스 등 에 저장할 때 쓰이는 방식

 

* 예제

 

메인 화면

Form1.vb

 

Imports System.Runtime.Serialization
Imports System.Collections

Public Class Form1
    Dim TT As T_TEST
    Dim t As clsTEST = New clsTEST

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        TT.strTEST = "객체 직렬화"
        t.FnTest = 15430305

        Using stm As System.IO.Stream = System.IO.File.Open("ect.class", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite)
            Dim bf As System.Runtime.Serialization.Formatters.Binary.BinaryFormatter = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
            '객체 직렬화 저장...
            bf.Serialize(stm, t)
            stm.Close()
        End Using
        TextBox1.Text += "Object Class" + vbCrLf
        TextBox1.Text += "lTest Value : " + t.FnTest.ToString() + vbCrLf
        TextBox1.Text += "객체 클래스 저장 완료..." + vbCrLf + vbCrLf


        Using stm As System.IO.Stream = System.IO.File.Open("ect.struct", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite)
            Dim bf As System.Runtime.Serialization.Formatters.Binary.BinaryFormatter = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
            '객체 직렬화 저장...
            bf.Serialize(stm, TT)
            stm.Close()
        End Using

        TextBox1.Text += "Object Struct" + vbCrLf
        TextBox1.Text += "sText Value : " + TT.strTEST + vbCrLf
        TextBox1.Text += "객체 구조체 저장 완료..." + vbCrLf

        TextBox1.Text += "=========================" + vbCrLf

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

        Using stm As System.IO.Stream = System.IO.File.Open("ect.class", System.IO.FileMode.Open, System.IO.FileAccess.Read)
            Dim bf As System.Runtime.Serialization.Formatters.Binary.BinaryFormatter = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter

            '역직렬화 후 객체 클래스로 형변환...
            Dim a As clsTEST = CType(bf.Deserialize(stm), clsTEST)
            stm.Close()

            TextBox1.Text += "Object Class" + vbCrLf
            TextBox1.Text += "lTest Value : " + a.FnTest().ToString() + vbCrLf
            TextBox1.Text += "객체 클래스 불러오기 완료..." + vbCrLf + vbCrLf

        End Using


        Using stm As System.IO.Stream = System.IO.File.Open("ect.struct", System.IO.FileMode.Open, System.IO.FileAccess.Read)
            Dim bf As System.Runtime.Serialization.Formatters.Binary.BinaryFormatter = New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter

            '역직렬화 후 객체 구조체로 형 변환...
            Dim a As T_TEST = CType(bf.Deserialize(stm), T_TEST)
            stm.Close()

            TextBox1.Text += "Object Struct" + vbCrLf
            TextBox1.Text += "sText Value : " + a.strTEST + vbCrLf
            TextBox1.Text += "객체 구조체 불러오기 완료..." + vbCrLf

        End Using
    End Sub
End Class


<Serializable()> Public Structure T_TEST
    Public strTEST As String
End Structure


<Serializable()> Public Class clsTEST
    Dim lTest As Long

    Public Sub New()
        lTest = 5
    End Sub

    Property FnTest() As Integer
        Get
            Return lTest
        End Get
        Set(ByVal value As Integer)
            lTest = value
        End Set
    End Property

    Public Function Test() As Long
        Return lTest
    End Function


End Class

* 객체 직렬화를 위해서는 그 선언 객체에 반드시 <Serializable()> 을 붙여 줘야 됨.

 

 

[C#] ▼

https://kdsoft-zeros.tistory.com/26

 

[C#] 객체 파일 저장 및 불러오기 예제 (Serialization)

* 객체 직렬화 (Serialization) - 객체를 메모리나 파일 , 데이터베이스에 저장할 때 쓰이는 방식 * 예제 Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System..

kdsoft-zeros.tistory.com

 

반응형
반응형

* 객체 직렬화 (Serialization)

 - 객체를 메모리나 파일 , 데이터베이스에 저장할 때 쓰이는 방식

 

* 예제

 

메인화면

Form1.cs

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ObjectSerialization_File
{

    public partial class Form1 : Form
    {
        //객체 저장을 위한 변수 선언...
        ObjectClass oc = new ObjectClass();
        ObjectStruct os = new ObjectStruct();

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //저장

            //객체 클래스 변수 값 변경...
            oc.FniValue = 1500;
            oc.FnjVlaue = 3000;

            using (System.IO.Stream stm = System.IO.File.Open("ect.dat", System.IO.FileMode.Create , System.IO.FileAccess.ReadWrite  ))
            {
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                //객체 직렬화 저장
                bf.Serialize(stm, oc);
                stm.Close();
            }

            textBox1.Text += "Object Class" + System.Environment.NewLine;
            textBox1.Text += "i Value : " + oc.FniValue.ToString() + System.Environment.NewLine;
            textBox1.Text += "j Value : " + oc.FnjVlaue.ToString() + System.Environment.NewLine;
            textBox1.Text += "i+j Value : " + oc.GetValue().ToString() + System.Environment.NewLine;
            textBox1.Text += "객체 클래스 저장 완료..." + System.Environment.NewLine;

            //객체 구조체 변수 값 변경...
            os.i = 30000;
            os.j = 40000;

            using (System.IO.Stream stm = System.IO.File.Open("ect2.dat", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
            {
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                //객체 직렬화 저장
                bf.Serialize(stm, os);
                stm.Close();
            }
            textBox1.Text += "Object Struct" + System.Environment.NewLine;
            textBox1.Text += "i Value : " + os.i .ToString() + System.Environment.NewLine;
            textBox1.Text += "j Value : " + os.j.ToString() + System.Environment.NewLine;
            textBox1.Text += "객체 구조체 저장 완료..." + System.Environment.NewLine;

            textBox1.Text += "===============" + System.Environment.NewLine;

        }

        private void button2_Click(object sender, EventArgs e)
        {
            ObjectClass LoadOC;
            ObjectStruct LoadOS;

            //불러오기
            using (System.IO.Stream stm = System.IO.File.Open("ect.dat", System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                //직렬화 된 객체 역직렬화 및 다시 객체 클래스로 형변환
                LoadOC = (ObjectClass) bf.Deserialize(stm);
                stm.Close();
            }

            textBox1.Text += "Object Class" + System.Environment.NewLine;
            textBox1.Text += "i Value : " + LoadOC.FniValue.ToString() + System.Environment.NewLine;
            textBox1.Text += "j Value : " + LoadOC.FnjVlaue.ToString() + System.Environment.NewLine;
            textBox1.Text += "i+j Value : " + LoadOC.GetValue().ToString() + System.Environment.NewLine;
            textBox1.Text += "객체 클래스 불러오기 완료..." + System.Environment.NewLine;

            using (System.IO.Stream stm = System.IO.File.Open("ect2.dat", System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                //직렬화 된 객체 역직렬화 및 다시 구조체로 형변환
                LoadOS  = (ObjectStruct) bf.Deserialize(stm)  ;
                stm.Close();
            }

            textBox1.Text += "Object Struct" + System.Environment.NewLine;
            textBox1.Text += "i Value : " + LoadOS.i.ToString() + System.Environment.NewLine;
            textBox1.Text += "j Value : " + LoadOS.j.ToString() + System.Environment.NewLine;
            textBox1.Text += "객체 구조체 불러오기 완료..." + System.Environment.NewLine;
        }
    }

    //객체 직렬화를 위한 클래스 선언...
    [Serializable]
    public class ObjectClass
    {
        int i = 300;
        int j = 100;

        public int FniValue
        {
            get { return i;}
            set { i = value;}
        }

        public int FnjVlaue
        {
            get { return j; }
            set { j = value; }
        }


        public int GetValue()
        {
            return i + j;
        }
    }

    //객체 직렬화를 위한 구조체 선언...
    [Serializable]
    public struct ObjectStruct
    {
        public int i;
        public int j;
    }
}

* 객체 직렬화를 위해서는 그 선언 객체에 반드시 [Serializable] 을 붙여 줘야 됨.

 

반응형
반응형

* 구조체를 Marshal 이용 바이트배열로 변환 하거나 바이트 배열화 된 구조체를 다시 원래 모습으로

   복귀 시키는 예제...

 

메인화면

Form1.cs

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Runtime.InteropServices;

namespace StructAndBytes
{
    public partial class Form1 : Form
    {
        //구조체 선언...
        struct t_Test
        {
            public int iTmp ;
            public string strTmp;
            public double dbTmp ;
            public float ftTmp ;
        }

        //구조체 변수 선언...
        t_Test tt = new t_Test();

        byte[] bTmp;


        public Form1()
        {
            InitializeComponent();

            //테스트 값 대입...
            tt.dbTmp = 0.12321312313;
            tt.iTmp = 123123;
            tt.strTmp = "테스트1";
            tt.ftTmp = 0.123213f;

        }

        #region 사용자 정의함수...
        private   byte[] StructToBytes(object obj)
        {
            //구조체 사이즈 
            int iSize = Marshal.SizeOf(obj);

            //사이즈 만큼 메모리 할당 받기
            byte[] arr = new byte[iSize];

            IntPtr ptr = Marshal.AllocHGlobal(iSize);
            //구조체 주소값 가져오기
            Marshal.StructureToPtr(obj, ptr, false);
            //메모리 복사 
            Marshal.Copy(ptr, arr, 0, iSize);
            Marshal.FreeHGlobal(ptr);

            return arr;
        }

        private T ByteToStruct<T>(byte[] buffer) where T : struct
        {
            //구조체 사이즈 
            int size = Marshal.SizeOf(typeof(T));

            if (size > buffer.Length)
            {
                throw new Exception();
            }

            IntPtr ptr = Marshal.AllocHGlobal(size);
            Marshal.Copy(buffer, 0, ptr, size);
            T obj = (T)Marshal.PtrToStructure(ptr, typeof(T));
            Marshal.FreeHGlobal(ptr);
            return obj;

        }
        #endregion

        //버튼 이벤트...
        private void button1_Click(object sender, EventArgs e)
        {
            bTmp = StructToBytes(tt);
            label1.Text = bTmp.Length.ToString() + " bytes";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            t_Test tTmp = ByteToStruct<t_Test>(bTmp);

            label2.Text = "int 값: " + tTmp.iTmp.ToString();
            label3.Text = "double 값: " + tTmp.dbTmp.ToString();
            label4.Text = "float 값: " + tTmp.ftTmp.ToString();
            label5.Text = "string 값: " + tTmp.strTmp;

        }



    }
}

 

* 실행한 결과...

 

 

반응형

+ Recent posts