I have text file like this:
11/18/2012 test1
11/19/2012 test2
11/20/2012 test3
11/21/2012 test4
11/22/2012 test5
11/23/2012 test6
11/24/2012 test7
11/25/2012 test8
How do I search for the current date and return the entire line containing that date? For instance, if I run the program today, it should return
11/18/2012 test1
Code:
string searchKeyword = monthCalendar1.SelectionStart.ToShortDateString();
string[] textLines = File.ReadAllLines(@"c:\temp\test.txt");
List<string> results = new List<string>();
foreach (string line in textLines)
{
if (line.Contains(searchKeyword))
{
results.Add(line);
listBox2.Items.Add(line);
}
}
First - split your text by lines. E.g. this way:
// string[] lines = File.ReadAllLines(@"c:\temp\test.txt");
string[] lines = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
Second - find lines which start with current date string in specified format:
string date = DateTime.Now.ToString("MM/dd/yyyy");
IEnumerable<string> results = lines.Where(l => l.StartsWith(date));
If you completely sure that there could be only one such line, then use
string result = lines.SingleOrDefault(l => l.StartsWith(date));
Here is your code fixed and reafactored (you should use custom date string format and use StartsWith instead of Contains)
string searchKeyword = monthCalendar1.SelectionStart.ToString("MM/dd/yyyy");
string[] textLines = File.ReadAllLines(@"c:\temp\test.txt");
foreach (string line in textLines.Where(l => l.StartsWith(searchKeyword)))
listBox2.Items.Add(line);
var matches = new List<string>();
var currentDate = DateTime.Now.ToString("dd/MM/yyyy");
using (StreamReader sr = new StreamReader("file.txt"))
{
var line = sr.ReadLine();
if(line.StartsWith(currentDate))
matches.Add(line);
}
To add them to the listbox:
foreach (var match in matches)
listBox.Items.Add(match);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With