954,518 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

read text file into memory and loop through lines

hi, i need to search the text file for lines repeatedly. so i want to read the text file into memory and iterate through lines.

i am able to iterate as follows but, for the next search i need to iterate from the beginning which will require data transfer between hard drive and memory. instead i want to read it all it once to memory then iterate through it.

TextReader tr = new StreamReader(fileName);
			string input = null;
			while ((input = tr.ReadLine()) != null)
				// some code


the above is not i want.

serkan sendur
Postaholic
Banned
2,062 posts since Jan 2008
Reputation Points: 854
Solved Threads: 127
 

i did something like this although it wasnt the way i liked it to be :

string lines = File.ReadAllText(openFileDialog1.FileName);
					foreach (ListViewItem lvi in listView1.Items)
					{
						if (lines.Contains(lvi.Text) == false)
							listView1.Items.Remove(lvi);
					}


it works.

serkan sendur
Postaholic
Banned
2,062 posts since Jan 2008
Reputation Points: 854
Solved Threads: 127
 

Load it up in to a generic string collection:

private void simpleButton1_Click(object sender, EventArgs e)
    {
      const string fileName = @"C:\File.txt";
      List<string> lines = new List<string>();
      lines.AddRange(File.ReadAllLines(fileName));
      Console.WriteLine(lines.Count);
    }
sknake
Industrious Poster
4,954 posts since Feb 2009
Reputation Points: 1,764
Solved Threads: 735
 

This is what I used in a similar situation:

string[] lines = System.IO.File.ReadAllLines(@fname);

then file becomes an array of lines, and can be iterated through at will.

Mortu
Newbie Poster
2 posts since May 2009
Reputation Points: 10
Solved Threads: 1
 

you two are lucky to increase your solved threads by one since i forgot to mark this as solved before you posted your similar suggestions :)
good catch :)

serkan sendur
Postaholic
Banned
2,062 posts since Jan 2008
Reputation Points: 854
Solved Threads: 127
 

Lucky us indeed :)

Good luck!

sknake
Industrious Poster
4,954 posts since Feb 2009
Reputation Points: 1,764
Solved Threads: 735
 

Indeed, all we need is luck :-)

Mortu
Newbie Poster
2 posts since May 2009
Reputation Points: 10
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You