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.

Recommended Answers

All 6 Replies

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.

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);
    }

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.

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 :)

Lucky us indeed :)

Good luck!

Indeed, all we need is luck :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.