This is a fairly common problem, so you should extend the string class with the flexible Between method. First you need to define an extension class:
public static class StringExtensions
{
public static String Between(this string mainString, string head, string tail)
{
int HeadPosition;
int TailPosition;
int ResultPosition;
int ResultLenght;
if (!mainString.Contains(head) && mainString.Contains(tail))
{
return null;
}
HeadPosition = mainString.IndexOf(head);
TailPosition = mainString.IndexOf(tail);
ResultPosition = HeadPosition + head.Length;
ResultLenght = TailPosition - ResultPosition;
return mainString.Substring(ResultPosition, ResultLenght);
}
}
Then all you have to do is call a new method for any line.
var logTime = "LastWrite Time Thu Dec 9 05:12:42 2010 (UTC)";
logTime = logTime.Between("Time","(UTC)").Trim();
Please note that Between will only be available if you use the namespace that you specified StringExtensions in.
source
share