Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to restart from the top when reading a file

Status
Not open for further replies.

lydiattc

Programmer
Jun 3, 2003
52
US
hi,

I'm new to C#. I need to read through a file twice, and I wonder if I can reset the pointer without close and reopen the file. Any help will be appreciated!

Lydia
 
What are you doing with that file read on second time?
Can you provide us more information on what you want to do with two time read?

Sharing the best from my side...

--Prashant--
 
Thanks for your reply. I'm processing a data file. This file contains hundreds of thousands lines. Each line is a record of a very long number. I need to read through it the first time to count the number of records to verify if this file is valid. Since the volunm of the data, I cannot store the records while I'm reading it. The second time when I go thourgh it, I need to extract a substring from each line and write it to another file.

What would be the best way to accomplish this?

Thanks,
Lydia
 
Why not just read the substring as you go through it the first time?

[red]"... isn't sanity really just a one trick pony anyway?! I mean, all you get is one trick, rational thinking, but when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick[/red]
 
Try the next and enjoy

Code:
            string file = "c://test.txt"; // The file's full path
            System.IO.StreamReader sr = new System.IO.StreamReader(file);

            string[] contents ={ }; // Hold the data
            long rows = 0;


            while (sr.Peek() != -1)
            {
                sr.ReadLine();
                rows++;
            }

            // Suppose that 100 lines (rows/records) are ok.
            if (rows != 100)
                MessageBox.Show("Invalid file...");
            else
            {
                // Go to the start
                sr.BaseStream.Seek(0, System.IO.SeekOrigin.Begin);
                
                contents = new string[100];
                int i = 0;

                while (sr.Peek() != -1)
                    contents[i] = sr.ReadLine();
            }

            sr.Close();
            sr = null;
            
            // All data are in 'contents [0 - 99]' array
            // Go on from here !
 
Woops

Code:
                while (sr.Peek() != -1)
                {
                    contents[i] = sr.ReadLine();
                    i++;
                }

This goes to the second while... I forgot to increment the integer 'i', in order to save the next line at the next position in the array.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top