C# Windows Form을 이용하여 INI 파일 생성하는 방법



이번 포스팅에서는 C# 언어를 이용하여 INI 파일을 만드는 방법에 대해서 알아 보도록 하겠습니다.

 

제가 C++ 언어를 이용하여 INI 파일을 만드는 방법에 대하여 소개를 한 적이 있기 때문에 INI 파일이 무엇이고, 어떻게 사용하고, 어떻게 구성이 되어 있는지에 관해서는 따로 설명을 드리지는 않도록 하겠습니다.

 

혹시 내용을 모르시는 분들은 아래 링크로 가셔서 개념을 익히시면 좋으실 것 같습니다.^^


http://afsdzvcx123.tistory.com/90

 

그러면 바로 실제 C# Windows Form을 이용하여 INI 파일을 어떻게 생성하고 또 생성한 파일을 어떻게 읽는지에 대하여 실습을 통하여 알아보도록 하겠습니다.

 

제일 먼저 Windows Form 프로젝트를 생성하여 주시고, Button 컨트롤 하나를 배치하여 속성을 아래와 같이 작성하여 주시기 바랍니다.






여기까지 진행을 하셨다면 이제 Config.cs 클래스 파일을 선언하여 안에 코드를 아래와 같이 작성을 해주시기 바랍니다.

 


 

[Config.cs]


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace test

{

    public static class Config

    {

        [System.Runtime.InteropServices.DllImport("kernel32")]

        public static extern int GetPrivateProfileString(string sAppName, string sKeyName, string sDefault, StringBuilder sReturnedString, int nSize,

            string sFileName);

 

        [System.Runtime.InteropServices.DllImport("kernel32")]

        public static extern int WritePrivateProfileString(string sAppName, string sKeyName, string sValue, string sFileName);

 

        public static string sINIPath = @"C:\범범조조\Config.ini"// Environment.CurrentDirectory + "\\Config.ini";

 

        /// <summary>

        /// Database IP

        /// </summary>

        public static string sDBIP = String.Empty;

 

        /// <summary>

        /// Databbase User

        /// </summary>

        public static string sDBUser = String.Empty;

 

        /// <summary>

        /// Database Password

        /// </summary>

        public static string sDBPw = String.Empty;

 

        /// <summary>

        /// Database Name

        /// </summary>

        public static string sDBName = String.Empty;

 

        /// <summary>

        /// FTP IP

        /// </summary>

        public static string sFTPIP = String.Empty;

 

        /// <summary>

        /// FTP Port

        /// </summary>

        public static string sFTPPort = String.Empty;

 

        /// <summary>

        /// FTP User

        /// </summary>

        public static string sFTPUser = String.Empty;

 

        /// <summary>

        /// FTP Password

        /// </summary>

        public static string sFTPPw = String.Empty;

 

 

        //false 틀리지않다 true 틀리다 

        public static bool bCheck = false;

 

        public static void LoadIniFIle()

        {

            StringBuilder Buf = new StringBuilder(1024);

 

            ///<summary>

            /// Database

            ///</summary>

            GetPrivateProfileString("SERVER""IP""127.0.0.1", Buf, 1024, sINIPath);

            sDBIP = Buf.ToString();

 

            GetPrivateProfileString("SERVER""USER""범범조조", Buf, 1024, sINIPath);

            sDBUser = Buf.ToString();

 

            GetPrivateProfileString("SERVER""PW""12345", Buf, 1024, sINIPath);

            sDBPw = Buf.ToString();

 

            GetPrivateProfileString("SERVER""DATABASE""범범", Buf, 1024, sINIPath);

            sDBName = Buf.ToString();

 

 

            ///<summary>

            /// FTP

            ///</summary>

            GetPrivateProfileString("FTP""IP""127.0.0.1", Buf, 1024, sINIPath);

            sFTPIP = Buf.ToString();

 

            GetPrivateProfileString("FTP""PORT""9999", Buf, 1024, sINIPath);

            sFTPPort = Buf.ToString();

 

            GetPrivateProfileString("FTP""USER""범범조조", Buf, 1024, sINIPath);

            sFTPUser = Buf.ToString();

 

            GetPrivateProfileString("FTP""PW""범범조조", Buf, 1024, sINIPath);

            sFTPPw = Buf.ToString();

        }

 

        public static void SavaIniFile()

        {

            ///<summary>

            /// Database

            ///</summary>

            WritePrivateProfileString("SERVER""IP", sDBIP, sINIPath);

 

            WritePrivateProfileString("SERVER""USER", sDBUser, sINIPath);

 

            WritePrivateProfileString("SERVER""PW", sDBPw, sINIPath);

 

            WritePrivateProfileString("SERVER""DATABASE", sDBName, sINIPath);

 

            ///<summary>

            /// FTP

            ///</summary>

            WritePrivateProfileString("FTP""IP", sFTPIP, sINIPath);

 

            WritePrivateProfileString("FTP""PORT", sFTPPort, sINIPath);

 

            WritePrivateProfileString("FTP""USER", sFTPUser, sINIPath);

 

            WritePrivateProfileString("FTP""PW", sFTPPw, sINIPath);

        }

 

        public static void WriteUpdatingInfo(bool b)

        {

            string sVal = b == true ? "true" : "false";

            WritePrivateProfileString("UPDATE""UPDATING", sVal, sINIPath);

        }

 

        public static string ReadUpdatingInfo()

        {

            StringBuilder Buf = new StringBuilder(1024);

            GetPrivateProfileString("UPDATE""UPDATING""", Buf, 1024, sINIPath);

 

            return Buf.ToString();

        }

    }

}

Colored by Color Scripter

cs


간단히 GetPrivateProfileString(), WritePrivateProfileString() 함수를 설명 드리자면

 

GetPrivateProfileString – 해당 INI파일 안에 있는 섹션, , 값을 읽어 오는 함수

WritePrivateProfileString – 해당 INI파일 안에 섹션, , 값을 쓰는 함수

 

라고 이해 하시면 되겠습니다.

 

그리고 중복실행 방지를 위해 Program.cs 코드를 아래와 같이 작성해 주시기 바랍니다.

 

[Program.cs]


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

using System;

using System.Collections.Generic;

using System.Diagnostics;

using System.Linq;

using System.Threading.Tasks;

using System.Windows.Forms;

 

namespace test

{

    static class Program

    {

        /// <summary>

        /// 해당 응용 프로그램의  진입점입니다.

        /// </summary>

        [STAThread]

        static void Main()

        {

            try

            {

                string sUpdateInfo = Config.ReadUpdatingInfo();

 

                Config.WriteUpdatingInfo(false);

 

                if (sUpdateInfo == "true")

                {

                    Application.EnableVisualStyles();

                    Application.SetCompatibleTextRenderingDefault(false);

                    Application.Run(new Form1());

                }

                else

                {

                    int cnt = 0;

 

                    Process[] procs = Process.GetProcesses();

 

                    foreach (Process p in procs)

                    {

                        if (p.ProcessName.Equals("test"== true)

                            cnt++;

                    }

 

                    if (cnt > 1)

                    {

                        MessageBox.Show("이미 실행중입니다.");

                        return;

                    }

                    else

                    {

                        Application.EnableVisualStyles();

                        Application.SetCompatibleTextRenderingDefault(false);

                        Application.Run(new Form1());

                    }

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message, "Program - Error");

            }

        }

    }

}

 

 

Colored by Color Scripter

cs

 

여기까지 하셨다면 맨 처음에 배치 시켰던 Button 컨트롤을 더블 클릭하여 클릭 이벤트 핸들러 함수 안에 다음과 같이 코드를 작성해 주시고 실행을 시켜 버튼을 클릭하시면 해당 경로에 Config.ini 파일이 제대로 생성 된 것을 확인 하실 수 있습니다.

 

[Test.cs]


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

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 test

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void btn_ini_Click(object sender, EventArgs e)

        {

            Config.LoadIniFIle(); // 해당 경로에 INI 파일 생성

            Config.SavaIniFile(); //Config.ini 파일 경로에 저장

        }

    }

}

 

Colored by Color Scripter

cs

 


 

[실행 결과]

이렇게 제대로 INI파일이 원하는 경로에 생성이 되었고 해당 섹션, , 값 까지 제대로 출력 되어있는 것을 확인 하실 수 있습니다.^^

 

감사합니다.^^


728x90

이 글을 공유하기

댓글

Designed by JB FACTORY