2012-12-16 5 views
3

다음 코드로 .txt 파일을 여러 줄 텍스트 상자로 읽으려고합니다. 파일 대화 상자 버튼을 완벽하게 작동 시키려고했으나 실제 텍스트를 텍스트 상자로 가져 오는 방법을 모르겠습니다. 여기 내 코드가있다. 도울 수 있니? 당신은 단지 전체 텍스트를 필요로하는 경우TextBox에 .txt 파일 읽기

private void button_LoadSource_Click(object sender, EventArgs e) 
    { 
     Stream myStream = null; 
     OpenFileDialog openFileDialog1 = new OpenFileDialog(); 

     openFileDialog1.InitialDirectory = "c:\\"; 
     openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; 
     openFileDialog1.FilterIndex = 2; 
     openFileDialog1.RestoreDirectory = true; 

     if (openFileDialog1.ShowDialog() == DialogResult.OK) 
     { 
      try 
      { 
       if ((myStream = openFileDialog1.OpenFile()) != null) 
       { 
        using (myStream) 
        { 
         // Insert code to read the stream here. 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); 
      } 
     } 
    } 

답변

20

, 당신은 기능 File.ReadAllText를 사용해야합니다 - 그것에게 dialoge (openFileDialog1.FileName)에서 선택한 파일 이름/경로를 전달합니다.

예를 들어 텍스트 상자에 내용을로드, 당신은 쓸 수 있습니다 :

textbox1.Text = File.ReadAllText(openFileDialog1.FileName); 

개방 및 사용하여 스트림이 조금 더 복잡하다, 그것을 위해 당신이 사용하여 보일 것 - 문

+0

을 그 완벽하게 일했습니다. 고맙습니다! – Jeagr