Stuck? Need help? Ask questions on our forums.
*/

Other Views

corner
*/

How to Browse and Read a Text File into a TextBox

How do I browse and read a text file into a TextBox?

You use the OpenFileDialog to implement this functionailty.

 
using System.Text; 
using System.IO; 
private void button1_Click(object sender, System.EventArgs e) 
{ 
  OpenFileDialog ofd = new OpenFileDialog(); 
  ofd.Title = "Open the text file you wish" ; 
  ofd.InitialDirectory = "c:\" ; 
  ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ; 
 
 if(ofd.ShowDialog() == DialogResult.OK) 
   { 
    StreamReader sr = File.OpenText(ofd.FileName); 
    string s = sr.ReadLine(); 
    StringBuilder sb = new StringBuilder(); 
    while (s != null) 
      { 
       sb.Append(s); 
       s = sr.ReadLine(); 
      } 
      sr.Close(); 
      textBox1.Text = sb.ToString(); 
   } 
}


Written by Sandeep Mogulla, Webmaster at www.startvbdotnet.com

C# FAQ Index
corner
© 1996-2008 CommunityHeaven LLC. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
North American business development: Nicolai Wadstrom. Publisher: Lars Hagelin.
Resource Listings