Normally I would advocate the use of the
String.Split Method[
^] but that can't be used here as the delimiters for the "sections" of the message actually form part of those sections (e.g. colon : is part of the date as well as terminating it)
So we have to use what we know about the format of the string - with some caveats!!
-- What if the date is "11/10/2013" - 10 characters long instead of the 9 in your example
-- What if the time is "11:19:05 PM" - 11 characters long instead of 10
What we do know is that the date is terminated by the
first space, and the time is terminated by either "AM:" or "PM:"
So the following would work ...
string s = "11/5/2013 6:19:05 PM:Invalid object name 'batchresult'. - at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)";
string d = s.Substring(0, s.IndexOf(' ')).Trim();
string t = s.Substring(d.Length + 1);
t = t.Substring(0, t.IndexOf("M:") + 1).Trim();
string r = s.Substring(s.IndexOf("M:") + 2);
Debug.Print(s);
Debug.Print(d);
Debug.Print(t);
Debug.Print(r);
DateTime d1;
bool b = DateTime.TryParse(d, out d1);
Debug.Print(d1.ToString());
The above code produced the output
11/5/2013
6:19:05 PM
Invalid object name 'batchresult'. - at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)