Fixer Fixer - 1 year ago 136
C# Question

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


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 Source

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"));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download