# Read/Write a TXT file with timestamp [closed]

I have write this code that read a txt file and re-write it whith the timestamp sorted.

This is the result (top image is input, bottom is output)

MY QUESTION IS: Anyone do you have a suggestion to optimize this code? Because this text is a little example,my code would work with txt more longer than it. (For example 50K-60K line)

Regards

static void Main(string[] args)
{

string[] str;

//Define regex string for MEX ETCS
string messageETCS = @"(\d){4}-(\d){2}-(\d){2}.*(?:\r?\n(?!\d{4}-\d{2}-\d).*)*";
Regex regMEXETCS = new Regex(messageETCS);

string regexDate = @"\d{4}-\d{2}-\d{2}";
Regex regDateETCS = new Regex(regexDate);

// Open the text file using a stream reader.
{
// Read the stream to a string, and write the string to the console.
String logContent = sr.ReadToEnd();

//run regex
List<String> MasterList = new List<String>(logContent.Length);
Match matchResults = regMEXETCS.Match(logContent);
Match onlyDate = regDateETCS.Match(logContent);
str = Regex.Split(logContent, @"\d{4}-\d{2}-\d{2}", RegexOptions.None);

while (matchResults.Success)
{

for (int j = 1; j < str.Length;j++ ) {

string t = str[j].TrimEnd();
matchResults = matchResults.NextMatch();
}
}

String date1 = onlyDate.ToString();
MasterList.Sort();
using (TextWriter tw = new StreamWriter(@"C:\output.txt"))
{
for (int i = 0; i < MasterList.Count; i++)
{
tw.WriteLine(date1 + MasterList[i]);
}
}
}
}

• Can you please replace the images with plain text? To format it well, you can use code-block format: copy-paste the text and press control K. May 7 '17 at 15:17
• It is difficult to tell just what can be done, because it isn't clear what format the input has. You are splitting by stuff that looks like a date, but with a better specification we can do a better job improving the input. As TheQult says in his answer, reading line-by-line will help a lot (List has good addition characteristics, so don't worry about defining the capacity in advance: what you have currently is way too big and runs the risk of exceeding the 2GB limit on strings). May 27 '17 at 8:47