I am writing a simple program which reads through a text file and searches for a specific string. As it finds each instance of this string it needs to copy the date and time of the line (not the text) into another text file. So for example if the text file contains the following:
22/12/10 08:45:07.514 Hello my name is
22/12/10 08:45:17.514 bye
22/12/10 08:45:27.514 Hello world
22/12/10 08:45:37.514 bye
22/12/10 08:45:47.514 Hello and bye world
22/12/10 08:45:57.514 bye
22/12/10 08:46:07.514 Hello my name is slim shady
And if the search string was "Hello", the result would be the date and time of the five lines containing this string are copied into another text file. The date and time needs to be in the format as shown in the example above (dd/mm/yy hh:mm:ss.sss).
I have made a start and manged to write the program so it searches the text file line by line and then copies the date and times of the lines containing the search string. It does this by removing the first 21 characters of the line wich matches the search criteria, see below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace Interrupt
{
class clsProgram
{
public static void Main(string[] args)
{
// initialise variables
int iCounter = 1;
string sLine;
StreamReader sr = new StreamReader(@"C:\C\sample.txt");
StreamWriter sw = new StreamWriter(@"C:\C\sample2.txt");
while ((sLine = sr.ReadLine()) != null)
{
if (sLine.Contains("Hello"))
{
string sNewLine = sLine.Remove(21)
Console.WriteLine(sNewLine);
sw.WriteLine(sNewLine);
}
iCounter++;
}
sr.Close();
sw.Close();
}
}
}
So when the program runs, the results is:
22/12/10 08:45:07.514
22/12/10 08:45:27.514
22/12/10 08:45:47.514
22/12/10 08:46:07.514
I need the program to be able to calculate the time difference between these lines and display them next to the line. So the result for the example above would be would be:
22/12/10 08:45:07.514
22/12/10 08:45:27.514 00:00:10.000
22/12/10 08:45:47.514 00:00:10.000
22/12/10 08:46:07.514 00:00:10.000
I would like this program to have error handling so please advise on the best way to complete it.
Please note the date and time part of the line is always the first 21 characters and never changes so this is why I wan to use the remove(21) method.
Thanks.
### Visual Studio 2008, .Net Framework 3.5 ###


Sign In
Create Account

Back to top










