CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Dec 2008
    Posts
    87

    Small File Input Problem

    I'm trying to make a simple program where a text file is read in and it prints the text in a textbox and the number of lines in the file. I cant get the number of lines to come up OK and get the file to display in the textbox. However I cannot get the program to do both these things in one program. Here is my code so far:

    Code:
    if (openFile.ShowDialog() == DialogResult.OK)
                {
                    //Create variable for storing the number of lines
                    int lines = 0;
                    string fileName = openFile.FileName;
                    StreamReader objReader = new StreamReader(fileName);
                    //Loop until we reach the end of the file and increase the line count
                    while (objReader.ReadLine() != null)
                    {
                        lines++;
                    }
                    //Print the contents of the file to the textbox
                    txtFile.Text = objReader.ReadToEnd();
                    lblLines.Text = lines.ToString();
                    objReader.Close();
                }

  2. #2
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Small File Input Problem

    You are using a stream, so when you call ReadLine( ) the position of the stream is being incremented. So, when you later call ReadToEnd( ) there is nothing left to read. Why not just create the string while you are looping through each line, i.e., get rid of the call to ReadToEnd( )?

  3. #3
    Join Date
    Nov 2007
    Location
    .NET 3.5 / VS2008 Developer
    Posts
    624

    Re: Small File Input Problem

    make sure you set the textbox for the text to be MultiLine.

    Code:
    OpenFileDialog ofd = new OpenFileDialog();
    if (ofd.ShowDialog() == DialogResult.OK)
    {
        StringBuilder sb = new StringBuilder();
        int counter = 0;
    
        using (TextReader tr = new StreamReader(ofd.FileName))
        {
            while (tr.Peek() >= 0)
            {
                sb.AppendLine(tr.ReadLine());
                counter++;
            }
        }
    
        txtText.Text = sb.ToString();
        txtCount.Text = counter.ToString();
    }
    ===============================
    My Blog

  4. #4
    Join Date
    Dec 2008
    Posts
    87

    Re: Small File Input Problem

    Managed to get it working, thanks

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

Featured