File name has two backslashes C#

て烟熏妆下的殇ゞ 提交于 2019-12-20 03:32:22

问题


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 becomes C:\\Temp which causes the file not to save.

This is the code in question

String fileName = @"C:\Temp\data_" + DateTime.Now.ToString() + ".txt";

For example the output could be C:\\Temp\\data_12/04/2012 20:08:40.txt

It should be C:\Temp\data_12/04/2012 20:08:40.txt


回答1:


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 :(




回答2:


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




回答3:


Try setting a format:

String fileName = @"C:\Temp\data_" + DateTime.Now.ToString("MM d HH mm yyyy") + ".txt";



回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/10130400/file-name-has-two-backslashes-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!