Live Chat Icon For mobile
Live Chat Icon

How do I browse for, and read a text file into an TextBox

Platform: WinForms| Category: TextBox

You use the Frameworks OpenFileDialog to implement this functionality.

	using System.Text;
	using System.IO;
	....
	private void button1_Click(object sender, System.EventArgs e)
	{
		OpenFileDialog dlg = new OpenFileDialog(); 
		dlg.Title = 'Open text file' ; 
		dlg.InitialDirectory = @'c:\' ; 
		dlg.Filter = 'txt files (*.txt)|*.txt|All files (*.*)|*.*' ; 
		 
		if(dlg.ShowDialog() == DialogResult.OK) 
		{ 
			StreamReader sr = File.OpenText(dlg.FileName);

			string s = sr.ReadLine();
			StringBuilder sb = new StringBuilder();
			while (s != null)
			{
				sb.Append(s);
				s = sr.ReadLine();
			}
			sr.Close();
			textBox1.Text = sb.ToString();
		} 
	}

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.