텍스트 파일 읽고 저장하기

 

 

private void button1_Click(object sender, EventArgs e)
{
	//FORM 실행 위치를 가져온다
    //System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(System.Windows.Forms.Application.StartupPath);
    
    //디렉토리를 지정한다
    System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@"C:\temp");
	
    //오류 발생시 알려준다
    try
    {
        //모든 줄 읽기(ReadAllText)
        //한글 오류 방지하기 위해  Encoding.Default 추가해준다
        
        //첫번째 방식 : string readtext = File.ReadAllText(@"c:\temp\test.txt", Encoding.Default);
        //두번째 방식 : StreamReader sr = new StreamReader(@"c:\temp\test.txt", Encoding.Default);
        
        StreamReader sr = new StreamReader(di.ToString() + @"\test.txt", Encoding.Default);
        string readtext = sr.ReadToEnd();
        sr.Close();
        
        //TextBox에 넣기
        textbox.Text = input;


        //한 줄 씩 읽기(ReadAllLines)
        string input = "";
        string[] lines = System.IO.File.ReadAllLines(@"C:\temp\test.txt", Encoding.Default);
        foreach (string show in lines)
        {
            if (input == "")
            {
                input = show;
            }
            else
            {
                input = input + "\r\n" + show;
            }
        }

        //TextBox에 넣기
        textbox.Text = input;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

}
Posted by agape93
,