File name has two backslashes C#

后端 未结 5 1434
甜味超标
甜味超标 2021-01-21 23:06

There is probably an easy answer for this, but when I added DateTime.Now.ToString() to my fileName it adds an extra \\ for every \\ I have so C:\\Temp

相关标签:
5条回答
  • 2021-01-21 23:33

    It is actually the forward slashes that are illegal in filename. Replace the forward slashes with something legal and try again.

    0 讨论(0)
  • 2021-01-21 23:34
    String fileName = String.Format(@"C:\Temp\data_{0}.txt",DateTime.Now.ToString("ddMMyyyyHHmmss"));
    

    Output: C:\Temp\data_12042012214358.txt

    or use

    String fileName = String.Format(@"C:\Temp\data_{0}.txt", DateTime.Now.ToString("dd.MM.yyyy HH-mm-ss"));
    

    Output: C:\Temp\data_12.04.2012 21-45-03.txt

    0 讨论(0)
  • 2021-01-21 23:41

    Nope, that string really has single backslashes in. Print it out to the console and you'll see that.

    If you look at it in the debugger, you'll see the backslashes escaped - but the string itself has single backslashes. This bites lots of people :(

    0 讨论(0)
  • 2021-01-21 23:45

    Try setting a format:

    String fileName = @"C:\Temp\data_" + DateTime.Now.ToString("MM d HH mm yyyy") + ".txt";
    
    0 讨论(0)
  • 2021-01-21 23:50

    Actually, it shows two backslashes in the variable value because the ­\ is escaped. If you print the variable value, you should see that it only have one backslash.

    0 讨论(0)
提交回复
热议问题