Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.replace removing backslash

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.

like image 346
nick gowdy Avatar asked Mar 16 '26 09:03

nick gowdy


2 Answers

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
like image 116
Jon Avatar answered Mar 18 '26 23:03

Jon


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(@"\", "-");
like image 31
Yazan Al-Alul Avatar answered Mar 18 '26 22:03

Yazan Al-Alul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!