본문 바로가기

C Sharp

C# ini file 예제.

반응형

C# ini file 예제.

IDE : Microsoft Visual Studio 2005

텍스트박스 2개, 체크박스 1개를 폼에 생성한후 폼이

종료될때 저장하고 폼이 나타날때 자동으로 로드하는 예제


using 문에 using System.Runtime.InteropServices 라이브러리 추가해주어야함.


전체 소스


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;


using System.Runtime.InteropServices;


namespace IniFileExample

{

public partial class Form1 : Form

{

[DllImport("kernel32")]

public static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);

[DllImport("kernel32")]

private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);


public Form1()

{

InitializeComponent();

}


public string GetIniValue(string section, string key, string filePath)

{

StringBuilder temp = new StringBuilder(255);

GetPrivateProfileString(section, key, "", temp, 255, filePath);

return temp.ToString();

}


private void Form1_FormClosed(object sender, FormClosedEventArgs e)

{

string sIniPath = 

System.Reflection.Assembly.GetExecutingAssembly().Location.ToLower().Replace(".exe", ".ini");

WritePrivateProfileString(this.Name, textBox1.Name, textBox1.Text, sIniPath);

WritePrivateProfileString(this.Name, textBox2.Name, textBox2.Text, sIniPath);

WritePrivateProfileString(this.Name, checkBox1.Name, checkBox1.Checked.ToString(), sIniPath);

}


private void Form1_Shown(object sender, EventArgs e)

{

string sIniPath = 

System.Reflection.Assembly.GetExecutingAssembly().Location.ToLower().Replace(".exe", ".ini");

textBox1.Text = GetIniValue(this.Name, textBox1.Name, sIniPath);

textBox2.Text = GetIniValue(this.Name, textBox2.Name, sIniPath);

checkBox1.Checked = 

GetIniValue(this.Name, checkBox1.Name, sIniPath).ToLower() == "true" ? true : false;

}


}

}

반응형