[C#] INI 읽고/쓰기

프로그래밍을 하다 보면 특정 환경 변수라던지 어떠한 값을 저장할 필요성이 있다.
예를 들어 DB 커넥션 정보라던지 ..
이럴때 레지스트리를 사용하거나 XML을 사용하거나 많은 방법이 있는데 그중에 손쉽게 ini 파일을 사용하여
저장 할 수 있다.

예) DB 접속 정보 저장:TNS, ID, PASSWORD 를 파일 정보에 넣어 놓고 읽고 갱신 할 수 있도록 해보자.
–걍 따라만 해도 됨.ㅋㅋ
1. iniUtil 이라는 클래쓰를 만들어 ini 관련 메소드를 구성해 놓자.(iniUtil.cs)
이 클래쓰 파일에 대해 크게 고민하지 말고 필요한 인자 값이 무엇인지 살펴보고 고대로 구성만 하면 되겠다.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
namespace INI{
class iniUtil
{
private string iniPath;
public iniUtil(string path)
{
this.iniPath = path;  //INI 파일 위치를 생성할때 인자로 넘겨 받음
}
[DllImport(“kernel32.dll”)]
private static extern int GetPrivateProfileString(    // GetIniValue 를 위해
String section,
String key,
String def,
StringBuilder retVal,
int size,
String filePath);
        [DllImport(“kernel32.dll”)]         private static extern long WritePrivateProfileString(  // SetIniValue를 위해
String section,
String key,
String val,
String filePath);
// INI 값을 읽어 온다.
public String GetIniValue(String Section, String Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, “”, temp, 255, iniPath);
return temp.ToString();
}
// INI 값을 셋팅
public void SetIniValue(String Section, String Key, String Value)
{
WritePrivateProfileString(Section, Key, Value, iniPath);
}
}
}
2. 필요한 곳에서 만들어 놓았던 iniUtil 의 객체를 생성해서 써보자.
– 파일 경로는 지금 프로그램이 실행 되고 있는곳으로 맞춰 놓고 사용하자. ini 파일 이름을 config.ini 로 가정한다면..
 //현재 프로그램이 실행되고 있는정보 가져오기: 디버깅 모드라면 bin/debug/프로그램명.exe
FileInfo exefileinfo = new FileInfo(Application.ExecutablePath);
string path = exefileinfo.Directory.FullName.ToString()  //프로그램 실행되고 있는데 path 가져오기
         string fileName = @”\config.ini”;  //파일명

 //만약 현재 실행 되는 경로가 아닌 특정한 위치를 원한다면 위에 과정 상관없이 바로
경로셋팅 해 주면 된다. 
(예: c:\config.ini)
string filePath = path+fileName;   //ini 파일 경로

iniUtil ini = new iniUtil(filePath);   // 만들어 놓았던 iniUtil 객체 생성(생성자 인자로 파일경로 정보 넘겨줌)

//이제 ini 객체를 이용해 맘것 사용하면 된다.

//값 셋팅하기
첫번째 인자: 섹션값(대분류로 생각하면 편함)
두번째 인자: 키값(구분값으로 생각)
세번째 인자: 실제 들어갈 값
ini.SetIniValue(“Oracle”, “OracleUser”          , “아이디”);
ini.SetIniValue(“Oracle”, “OraclePassword”  , “패스워드”);
ini.SetIniValue(“Oracle”, “TnsName”            , “TNS 이름”);
// 이렇게 하면 실제 config.ini 파일에는  아래처럼 저장 된다.
[Oracle] //첫번째 인자로 들어온 섹션값(대분류)
OracleUser=아이디
OraclePassword=패스워드
TnsName=TNS 이름

//값 가져와 사용하기
첫번째 인자: 섹션값(대분류로 생각하면 편함)
두번째 인자: 키값(구분값으로 생각)
string OracleUser           = ini.GetIniValue(“Oracle”, “OracleUser”);
string OraclePassword   = ini.GetIniValue(“Oracle”, “OraclePassword”);
string TnsName              = ini.GetIniValue(“Oracle”, “TnsName”);
 

“[C#] INI 읽고/쓰기”의 31개의 댓글

  1. Hi there, just became aware of your blog through Google, and found that it’s really
    informative. I’m gonna watch out for brussels. I will be grateful if you continue this in future.
    A lot of people will be benefited from your writing. Cheers!

  2. Hi there! I could have sworn I’ve visited this web site
    before but after going through some of the posts I realized it’s new to me.
    Nonetheless, I’m certainly pleased I found it and I’ll be book-marking it and checking back frequently!

  3. Howdy! Do you know if they make any plugins to assist with SEO?
    I’m trying to get my blog to rank for some targeted keywords but
    I’m not seeing very good success. If you know of any please share.
    Cheers!

  4. I just want to mention I am just beginner to weblog and absolutely savored your web-site. Likely I’m want to bookmark your blog . You absolutely come with terrific posts. Thank you for sharing with us your website page.

  5. Its such as you read my mind! You appear to understand a lot about this, like you wrote the e-book in it or something. I believe that you simply could do with a few to force the message house a bit, however other than that, this is wonderful blog. A great read. I’ll certainly be back.

  6. I enjoy you because of all of the effort on this web page. My daughter loves carrying out research and it’s really easy to see why. Almost all know all regarding the dynamic means you convey both interesting and useful steps through your web site and as well as invigorate participation from other individuals on this area of interest so our favorite girl has been being taught so much. Have fun with the remaining portion of the year. You are always doing a superb job.

  7. Attractive section of content. I just stumbled upon your web site and in accession capital to assert that I acquire in fact
    enjoyed account your blog posts. Any way I
    will be subscribing to your augment and
    even I achievement you access consistently fast.

  8. Oh my benefits! an amazing post guy. Thanks However I am experiencing issue with ur rss. Don?t recognize why Unable to sign up for it. Exists anybody obtaining the same rss trouble? Any individual who recognizes kindly react. Thnkx

  9. An outstanding share, I simply provided this onto an associate that was doing a little analysis on this. As well as he as a matter of fact acquired me breakfast due to the fact that I found it for him. smile. So let me reword that: Thnx for the treat! Yet yeah Thnkx for investing the time to review this, I feel strongly about it and love finding out more on this topic. Preferably, as you become competence, would you mind upgrading your blog site with even more information? It is very useful for me. Large thumb up for this article!

  10. I am frequently to blog writing and also i actually value your content. The short article has actually peaks my rate of interest. I am mosting likely to bookmark your site and keep looking for new info.

  11. I?m amazed, I need to state. Actually hardly ever do I run into a blog site that?s both educative as well as amusing, and let me tell you, you have hit the nail on the head. Your idea is exceptional; the issue is something that inadequate people are talking smartly about. I am really satisfied that I stumbled across this in my look for something associating with this.

  12. Can I just say what a relief to locate someone that really recognizes what theyre talking about on the web. You most definitely understand how to bring a problem to light as well as make it vital. Even more individuals need to read this and also recognize this side of the story. I cant believe youre not much more preferred since you most definitely have the gift.

  13. Oh my benefits! an incredible short article dude. Thanks Nevertheless I am experiencing issue with ur rss. Don?t recognize why Incapable to subscribe to it. Exists anybody obtaining identical rss trouble? Anybody that recognizes kindly react. Thnkx

  14. I discovered your blog website on google and also examine a few of your early messages. Remain to keep up the very good operate. I just additional up your RSS feed to my MSN News Viewers. Looking for onward to reading more from you later!?

댓글 남기기