Click here to Skip to main content
12,294,775 members (64,488 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C#2.0 C#3.0 C# C#4.0
I need to read a textfile with extention .txt and let is show into a textbox within a C# program.
The code I created only show me the path I entered but doesn't load in the text from the txtfile.

This is the code I got so far.

Any ideas on how to load in the text in the file instead

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string value = @"C:\Users\Respawn\Documents\AllTxtFiles.txt";
            StringReader OpenFile = new StringReader(value) ;
            textBox1.Text = OpenFile.ReadToEnd();
        }
Posted 15-Feb-13 2:16am
Edited 15-Feb-13 2:18am
v2
Comments
Abhishek Pant 15-Feb-13 8:47am
   
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Need to use a Stream Reader

StreamReader OpenFile = new StreamReader(value);
textBox1.Text = OpenFile.ReadToEnd();
OpenFile.Close();
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

Hi,

As alternative to Solution 1, you can use File.ReadAllText[^] to read all text from a file:
string s = File.ReadAllText(@"C:\Users\Respawn\Documents\AllTxtFiles.txt");
textBox1.Text = s;
Hope this helps.
  Permalink  
v2
Comments
Chris Reynolds (UK) 15-Feb-13 8:29am
   
Even nicer
ProgramFOX 15-Feb-13 8:30am
   
Thank you!
Abhishek Pant 15-Feb-13 8:50am
   
good one.+5
ProgramFOX 15-Feb-13 9:00am
   
Thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160525.2 | Last Updated 15 Feb 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100