Fixer Fixer - 13 days ago 5
C# Question

How to Parse a date string from a text file on PC to DateTime


---EDITED---


I have a simple C# Windows Form. "c:\date.txt" is just (DateTime.Now). Later I will create some code to update this file, but for now, I'm having a problem with debugging. It builds fine, but debug throws an exception at the date.txt file... The code is as follows:

public partial class Form1 : Form
{
private void timer1_Tick(object sender, EventArgs e)
{
DateTime dt = DateTime.Parse(@"C:\date.txt"); // Exception Thrown Here
// Should be: (File.ReadAllText(@"C:\date.txt"))
DateTime dn = DateTime.Now;
TimeSpan dc = (dn - dt);
label1.Text = ("Days = " + dc.Days +
"\nHours = " + dc.Hours +
"\nMins = " + dc.Minutes +
"\nSecs = " + dc.Seconds);
}
}


FormatException was unhandled... The string was not recognized as a valid DateTime. There is an unknown word starting at index 0. "When converting a string to DateTime, parse the string to take the date before putting each variable into the DateTime object."

I am parsing! I've tried (new StreamReader...ToString()). I've tried Convert.ToDateTime(...). I've tried making it a method... I've tried TryParse. Nothing is helping. What do I need to do here to make this thing read the string from the file?

Answer

If the file only contains a single line that contains a date, you can do this:

DateTime dt = DateTime.Parse(File.ReadAllText(@"C:\date.txt"));
Comments