简体   繁体   中英

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.

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(@"\", "-");

Direct System.DateTime.Now.Date.ToString('MM-dd-yyyy');

OR DateTime Date With Time

string newDate = DateTime.Now.ToString().Replace('/','-');

or Date Only

string newDate = DateTime.Now.Date.ToString().Replace('/','-');

out put

9-27-2012 5:20:12 PM

nothing to do split or convert ToString()

string DateNow = System.DateTime.Now.ToString("yyyy-MM-dd");

insted yyyy-MM-dd you also write yyyy/MM/dd

Check this link for more date formate Dateformate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM