개발자/C#

C# 파일 없으면 만들어 쓰고 있으면 한줄씩 읽어오는 코드

지구빵집 2012. 7. 20. 18:28
반응형




     


Telerik 사의 Radcontrol 사용해서 UI 만드는 중에 파일을 읽어오고 만들고 코드를 만드는 중입니다.


기회가 되면 RadControls for WinForms 에 대해 조금씩 포스팅을 할 예정입니다. 이쁘기도 하고 강력한 기능들이 많죠.


아래가 정해진 파일을 검사해서 파일이 실행파일과 같은 디렉토리에 있으면 정해진 변수에 한쭐씩 읽어서 할당하고

없으면 파일을 만드는 함수를 호출합니다.





private void Load_Initvaluefile()

{

FileStream fs = null;

StreamReader sr = null;


string Initialsetupfile = "initsetup.ini";


if (!File.Exists(Initialsetupfile)) // If the file does not exist 

{

make_setupfile();

}

else

{

try

{

fs = new FileStream(Initialsetupfile, FileMode.OpenOrCreate, FileAccess.Read);

sr = new StreamReader(fs, Encoding.Default);

string message = string.Empty;


/*while ((message = sr.ReadLine()) != null)

{

// setup after read state

}*/



string message1 = sr.ReadLine().ToLower(); // fan number

string message2 = sr.ReadLine().ToLower(); // cfm of fan

string message3 = sr.ReadLine().ToLower();  // volumn

}

catch (IOException ee)

{

MessageBox.Show(ee.Message);

}

finally

{

sr.Close();

fs.Close();

}

}

}


파일이름을 할당하고요~ 실행파일이 있는 위치에 파일이 있는지 검사하고

파일이 없으면 make_setupfile(); 를 실행합니다. 소스는 아래에~


파일이 있는 경우 위에서 생성한 파일 스트림과 스트림 리더를 사용해서 한줄씩 읽어다가 변수에 넣는데 

스트링이나 정수 실수 타입으로 파싱해서 집어 넣으면 됩니다.


try, catch, finally 를 사용해서 에러처리 까지 친절하게 해주고 반드시 파일 스트림과 스트림 리더는 닫아주어야 합니다.


아래는 make_setupfile(); 의 코드입니다. 초기값 - 디폴트값으로 한줄씩 써주게 되면 파일이 만들어지죠..


private void make_setupfile()

{

FileStream fs = null;

StreamWriter sw = null;


string setupfile = "initsetup.ini";


try

{

fs = new FileStream(setupfile, FileMode.OpenOrCreate, FileAccess.Write);

sw = new StreamWriter(fs, Encoding.Default);

string message = string.Empty;


sw.WriteLine("2");

sw.WriteLine("18.8");

sw.WriteLine("7");

}


catch (IOException ee)

{

MessageBox.Show(ee.Message);

}

finally

{

sw.Close();

fs.Close();

}

}


파일스트림과 스트림 리더를 생성하고 파일 이름을 정해주고, 파일 오픈해서 내용을 써주고 마찬가지로

try, catch, finally 사용해서 에러 처리를 해주고 닫습니다.


이런것들을 많이 라이브러리 화 해놓으면 - 파일네임 하나 던져주면서 객체 생성하는 방식으로 - 코딩하는게 편해지겠죠~


도움되었으면 합니다. 이만 총총...




반응형