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