Results 1 to 3 of 3

Thread: Reading a text file using C#

  1. #1

    Thread Starter
    Addicted Member DJ_Catboy's Avatar
    Join Date
    Jan 2003
    Location
    Suffolk, UK
    Posts
    159

    Reading a text file using C#

    Hi,

    I may be completely stupid but I can't make the code below work?! The text file TEST.TXT is a one liner (attached) and it is still not working!!!!! Please can somebody help me...... this was copied straight from MSDN...

    Code:
    using (StreamReader sr = new StreamReader("c:\\TEST.TXT")) 
    {
    String line;
    while ((line = sr.ReadLine()) != null) 
    {
    tb.AppendText(line + Environment.NewLine);
    }
    }
    I receive the error as follows:
    Index and Length must refer to a location within the string.
    Does anybody know what I am doing wrong?

    Thanks in advance,
    DJ
    Attached Files Attached Files

  2. #2
    Frenzied Member Memnoch1207's Avatar
    Join Date
    Feb 2002
    Location
    DUH, Guess...Hint: It's really hot!
    Posts
    1,861
    is there more you are trying to do, because the code you posted works fine for me.

    What I have...
    textbox (txtCheck) with multiline property set to true.
    and a button
    Code:
    private void button1_Click(object sender, System.EventArgs e)
    {
        StreamReader sr = new StreamReader("c:\\TEST.TXT");
    
        String line;
        while ((line = sr.ReadLine()) != null) 
        {
            txtCheck.AppendText(line + Environment.NewLine);
        }
    }
    Last edited by Memnoch1207; Jan 26th, 2004 at 02:30 PM.
    Being educated does not make you intelligent.

    Need a weekend getaway??? Come Visit

  3. #3
    ex-Administrator brad jones's Avatar
    Join Date
    Nov 2002
    Location
    Indianapolis
    Posts
    6,614
    I agree--the code looks good. I threw this into a console application and instead of using a control, threw the read text into a StringBuilder object:

    Code:
    using System;
    using System.Text;
    using System.IO;
    
    class test
    {
      public static void Main()
      {
        StringBuilder tb = new StringBuilder();
    
        using (StreamReader sr = new StreamReader("c:\\TEST.TXT"))
        {
          String line;
          while ((line = sr.ReadLine()) != null)
          {
            tb.Append(line + Environment.NewLine);
          }
      }
      Console.WriteLine(tb);
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width