Windows Service gives String was not recognized as a valid DateTime exception but the same code running properly in Console Application
Object max = cmd.ExecuteScalar(); //max will have 6/30/2012 12:00:00 AM
DateTime currentDt = DateTime.Now;
currentDt = DateTime.ParseExact(max.ToString(), "M/d/yyyy h:mm:ss tt", CultureInfo.CurrentCulture.DateTimeFormat); //This Line Gives Error in WindowsService Only
StreamWriter sw = new StreamWriter("E:\\ram\\SampleService.txt", true);
sw.WriteLine(currentDt.ToString());
sw.Close();
I even Changed System DateTime Format Settings to Engish – Us Settings.ShortDatetime is M/d/yyyy and Longtime is h:mm:ss tt.
Can someone help me resolve this issue?
My guess is that the system locale isn’t the same as your user locale. If your system locale uses something other than “/” as the date separator, it will fail to match the “/” in your format string.
I suggest you change to use
CultureInfo.InvariantCulture, at which point it should work – if the value ofmax.ToString()is actually “6/30/2012 12:00:00 AM”. Have you validated that in the case it’s failing, that’s the value you’re getting?If your value is coming from a database though, why is it stored as a string to start with? Are you sure it even is a string? If it’s actually a
DateTime, then when you callToString()you’ll be using the current culture’s default format to convert it – which could easily fail on the way back. Even if it is a string at the moment, does it really have to be? The fewer string conversions you can introduce, the better.(As an aside, it’s simpler to use
File.WriteAllTextorFile.AppendAllTextthan using aStreamWriterlike this. If you do need to use aStreamWriter, remember to use ausingstatement to dispose of the resource properly.)