I have a question and I am sure it is simple but its not working in my code. I am creating a log file and I want to concatenate the date to the file name so they know when the log was generated. My string.replace isn't removing "\" from my date which I have converted to string.
See code below:
string DateNow = Convert.ToString(System.DateTime.Now);
DateNow = DateNow.Substring(0, 10);
DateNow.Replace(@"\\", "-");
string FileName = "log" + DateNow + ".txt";
// Write values to textfile and save to Log folder
using (StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath("~/Log" + FileName)))
{
sw.WriteLine(System.DateTime.Now);
sw.WriteLine("New user created");
sw.WriteLine("Username is: " + username);
sw.WriteLine("Password is: " + password);
sw.WriteLine("Company is: " + company);
sw.WriteLine("Email is: " + email);
sw.Dispose();
sw.Close();
}
This will throw an exception because file names in windows can't contain \ character. Any ideas why the replace method isn't working?
Thanks.
It's working, but you are not storing the result. It needs to read
DateNow = DateNow.Replace(@"\", "-");
But that's simply a patch for a bad solution. Why not do it the right way in the first place? Use DateTime.ToString with a custom format string instead. For example:
string DateNow = System.DateTime.Now.ToString("yyyy-MM-dd"); // or any other format
You've already escaped the backslash using the @ symbol, so the replace function is looking for "\\", not "\". To make your code work, change it to:
DateNow = DateNow.Replace(@"\", "-");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With