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