본문 바로가기

Winform

[Winform] TextBox 문자열 기록 (File Read/Write, FormClosed)

반응형

- 저는 IP와 PORT 번호로 예를 들겠습니다. 

1. Label, TextBox

- 실행을 할 때마다 IP와 PORT 번호를 일일이 쳐야 되는 아주 귀찮게 되는데, 

- TextBox로 쓴 IP와 PORT 번호를 txt나 ini 파일로 기록을 해서 다음에 실행을 할 때 치지 않고 자동으로 문자열이 입력되게 구현을 하겠습니다.

 

- 우선 도구상자를 열어서 Label로 IP : PORT : 를 만들어줍니다.

- 그리고 각각 IP와 PORT를 입력받게 할 TextBox를 만들어줍니다.

 

- TextBox(Name)

- 그리고 TextBox 두 개를 각각 더블 클릭 해주고,

- 코드를 작성해줍니다.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace StringReport
{
    public partial class Form1 : Form
    {
        static public string m_strIP = string.Empty;
        static public string m_strPORT = string.Empty;
 
        public Form1()
        {
            InitializeComponent();
        }
 
        // IP의 textBox를 더블클릭하면 함수 자동으로 생성
        private void IP_textBox_TextChanged(object sender, EventArgs e)
        {
            m_strIP = IP_textBox.Text;
        }
 
        // PORT의 textBox를 더블클릭하면 함수 자동으로 생성
        private void PORT_textBox_TextChanged(object sender, EventArgs e)
        {
            m_strPORT = PORT_textBox.Text;
        }
    }
}
 
cs

 

2. Form_Closed (폼 닫기 이벤트)

- 폼을 닫을 때 실행파일에 프로젝트 이름 .txt를 만들어서 거기에 IP, PORT 번호를 저장해 줄 겁니다.

- Form1.cs[디자인] 속성에서 빨간색 박스 번개 모양 클릭 후, FormClosed에서 함수를 만듭니다.

- 저는 Form1_Closing으로 하겠습니다.

- 저 상태에서 Enter를 누르면 이것도 역시 자동으로 함수 코드가 생성됩니다.

// Form Closed Event Function
private void Form1_Closing(object sender, FormClosedEventArgs e)
{
 
}
cs

 

- 이제 폼을 닫을 때 실행파일에 파일이 생성되고, IP와 PORT 번호를 파일에 저장하는 구현을 하겠습니다.

 

3. 구현 (파일에 IP, PORT 번호 저장)

3.1 파일 경로

- 파일에 관해서 코딩을 한다면 위에 using System.IO; 꼭 추가해 주세요

- Application.ProductName == 현재 프로젝트 이름

- System.IO.Directory.GetCurrentDirectory() == 실행 파일 경로

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;    // File 관련 (추가)
 
namespace StringReport
{
    public partial class Form1 : Form
    {
        static public string m_strIP = string.Empty;
        static public string m_strPORT = string.Empty;
        static public string m_strPath = string.Empty;
 
        public Form1()
        {
            InitializeComponent();
 
            // 현재 프로젝트 이름
            string strProjectName = Application.ProductName + ".txt";
 
            // 실행 파일 경로 + 프로젝트 이름
            m_strPath = System.IO.Directory.GetCurrentDirectory() + "/" + strProjectName;
        }
 
        // IP의 textBox를 더블클릭하면 함수 자동으로 생성
        private void IP_textBox_TextChanged(object sender, EventArgs e)
        {
            m_strIP = IP_textBox.Text;
        }
 
        // PORT의 textBox를 더블클릭하면 함수 자동으로 생성
        private void PORT_textBox_TextChanged(object sender, EventArgs e)
        {
            m_strPORT = PORT_textBox.Text;
        }
 
        // Form Closed Event Function
        private void Form1_Closing(object sender, FormClosedEventArgs e)
        {
            FileWriteIpPort(m_strIP, m_strPORT);
        }
 
        // 실행 파일 경로에 파일이 있으면,
        private void FileWrite(string path, string message)
        {
            if(m_strPath != string.Empty)
            {
                // AppendAllText == 기존 파일 내용에 덧붙인다.
                File.AppendAllText(path, message);
            }
        }
 
        // 파일에 IP=000 PORT=000 이런 구조로 저장
        private void FileWriteIpPort(string ip, string port)
        {
            string temp = string.Empty;
            if (ip != string.Empty)
            {
                temp = "IP=" + ip;
                FileWrite(m_strPath, temp);
                FileWrite(m_strPath, "\r\n");
            }
            if (port != string.Empty)
            {
                temp = "PORT=" + port;
                FileWrite(m_strPath, temp);
                FileWrite(m_strPath, "\r\n");
            }
        }
    }
}
 
cs

 

- 여기까지 작성을 하셨으면 실행을 해 보겠습니다.

- 1234, 5678 작성을 하고 폼을 종료를 하면,

 

- 실행 파일 경로는

- 프로젝트이름/bin/Debug 에 있습니다.

- 파일이 생성되고 들어가면, IP와 PORT 번호가 저장된 것을 확인하실 수 있습니다.

 

- 근데 한번 더 실행을 해보면 아직 문자열이 기록이 안되어있습니다. 이제 그걸 구현하겠습니다.

 

4. 구현 (TextBox에 IP, PORT 번호 기록)

- public Form1()

        public Form1()
        {
            InitializeComponent();
 
            // 현재 프로젝트 이름
            string strProjectName = Application.ProductName + ".txt";
 
            // 실행 파일 경로 + 프로젝트 이름
            m_strPath = System.IO.Directory.GetCurrentDirectory() + "/" + strProjectName;
 
            // 파일 존재 유무 확인
            if (false == File.Exists(m_strPath))
            {
                // m_strPath에 파일이 존재하지 않으면 (false) 파일 생성
                FileStream fs = new FileStream(m_strPath, FileMode.Create);
                fs.Close();
            }
            else //(true == File.Exists(m_strPath))
            {
                int cnt = 0;
                StreamReader reader = null;
                using(reader = new StreamReader(m_strPath))
                {
                    List<string> list = new List<string>();
                    while(!reader.EndOfStream)
                    {
                        string line = reader.ReadLine();
                        list.Add(line);
                        cnt++;
                    }
 
                    if(list.Count != 0 && cnt!=0)
                    {
                        // ex) IP=127.0.0.1 
                        // Split('=') == ('=' 문자 기준으로 문자열 짜름)
                        // strGetIP[0] = IP
                        // strGetIP[1] = 127.0.0.1
                        string[] strGetIP = list[cnt - 2].Split('=');
                        string[] strGetPORT = list[cnt - 1].Split('=');
 
                        // cnt의 의미는 실행할때마다 IP와 PORT번호가 파일에 저장되는데
                        // 가장 최근에 입력한 IP와 PORT 번호가 파일끝에 추가(누적)되기 있기 때문에 cnt를 씀
 
                        // IP를 IP_TextBox에 넣음
                        IP_textBox.Text = strGetIP[1];
 
                        // PORT를 PORT_TextBox에 넣음
                        PORT_textBox.Text = strGetPORT[1];
                    }
                }
            }
        }
cs

 

5. Result

- 실행되면 TextBox에 기록되는 것을 볼 수 있습니다.

- 이번에는 IP = 127.0.0.1 PORT = 8000으로 해보겠습니다.

- TextBox에 입력해 주고 닫기 버튼을 누릅니다.

- 파일에는 저장이 잘 되었고

- 다시 실행을 하면 기록이 된 것을 확인하실 수 있습니다.

 

- 이상으로 포스팅 마치겠습니다 감사합니다.

StringReport.zip
0.05MB

 

반응형