.NET StringBuilder and verbatim string literal

1k Views Asked by At

In my Application there is a class that works with PdfSharp to generate some PDF reports. I specified output folder as a string with verbatim

string file_path = @"D:\Intranet\Students\DailyMarks\";

Also there is a StringBuilder that generates file name based on some ID and DateTime:

... sb.Append(document.Type); sb.Append(document.Id); sb.Append(DateTime.Now.ToShortString());

And finally I do the following

file_path + sb.toString();

But my Application cathes an exception. After debugging session I see that actually my file_path is

file_path = "D:\\Intranet\\Students\\DailyMarks\\...";

As I understand it happens after concatenation of origin file with StringBuilder's toString() call. I tried to replace file_path string with something like this:

file_path = file_path.Replace(@"\\",@"\");

but it doesn't work. Where did I do wrong?

3

There are 3 best solutions below

1
On BEST ANSWER

Probably this is caused by the DateTime.Now.ToShortString() method, which adds forbidden characters to the path (:).

0
On

It's totally fine.

"D:\\Intranet\\Students\\DailyMarks\\..." == @"D:\Intranet\Students\DailyMarks\..."

In regular string you need to escape slashes, in verbatim it's done automatically

0
On

Another similar situation I faced today was about sending Japanese 「:」 (colon with whole inside) as a file's name's element and it worked. I wonder, why Russian colon calls an exception and Japanese not. Very interesting.