I have been toying around with virtual mode in listview and am trying to read a log file that is approx 300mb and this is my code so far. it freezes when it is loaded, but im using virtual mode and only calling readlines when needed. i feel like im missing something, anybody help?
public partial class Form1 : Form
{
private const int maxLines = 100;
List<string> list = new List<string>();
public Form1()
{
InitializeComponent();
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
foreach (string s in openFileDialog1.FileNames)
{
listBox1.Items.Add(s);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
listView1.VirtualMode = true;
listView1.VirtualListSize = maxLines;
PropertyInfo aProp = typeof(ListView).GetProperty("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance);
aProp.SetValue(listView1, true, null);
}
private void listView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = retrieveItem(e.ItemIndex);
listView1.VirtualListSize = addList(textBox1.Text);
ListViewItem.ListViewSubItem lvsi = new ListViewItem.ListViewSubItem();
NumberFormatInfo nfi = new CultureInfo("de-DE").NumberFormat;
nfi.NumberDecimalDigits = 0;
lvsi.Text = e.ItemIndex.ToString("n", nfi);
lvi.SubItems.Add(lvsi);
e.Item = lvi;
}
string retrieveItem(int index)
{
list.Clear();
addList(textBox1.Text);
return list[index];
}
int addList(string keyword)
{
list.Clear();
int counter = 0;
foreach (string line in File.ReadLines("test.log"))
{
if (line.Contains(keyword))
{
list.Add(line);
counter++;
}
}
return counter;
}
private void button1_Click(object sender, EventArgs e)
{
ListViewItem foundItem = listView1.FindItemWithText(textBox1.Text, false, 0, true);
if (foundItem != null)
{
listView1.TopItem = foundItem;
}
}
Use a streamReader rather than a file.readline to get the file contents because this will help if you are having memory issues. You could also use an asynchfilestream object.
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
Console.WriteLine(sr.ReadLine());
}
}
if you can use newer 4.5 tech
String result;
using (StreamReader reader = File.OpenText("existingfile.txt"))
{
Console.WriteLine("Opened file.");
result = await reader.ReadLineAsync();
Console.WriteLine("First line contains: " + result);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.