C# - Illegal characters in path

Simon picture Simon · Jun 10, 2016 · Viewed 12k times · Source

I have a database table that containing file paths of excel files that I import using a C# script.

The script works fine unless the filepath contains spaces e.g. C:\Temp\My Excel File.xls and I get an Illegal characters in path error message. Unfortunately I am not able to change the file names at the source.

If I hard code the file path to be as below it works fine.

String Filepath = @"C:\Temp\My Excel File.xls";

How do I alter this so I can include a string variable that will store the filepath from the database e.g.

String Filepath = //Code to get FilePath from database

StringCorrectedFilePath = @+FilePath;

Thanks in advance of any help

Edit: Issue is caused by files that start with a number creating invalid escape sequence. e.g. C:\Temp\20160611 My Excel File.xls

Edit 2: SOLVED - Error was caused by carriage return characters appearing after the file extension. Please see my answer for the solution.

Answer

Hans Kesting picture Hans Kesting · Jun 10, 2016

Whether you do this

String Filepath = @"C:\Temp\My Excel File.xls";

or this

String Filepath = "C:\\Temp\\My Excel File.xls";

the string stored in memory is just C:\Temp\My Excel File.xls, whatever the debugger may tell you. So when you read some string from somewhere (database, file, user input, ...) you don't need to "escape" backslashes. So just use that string.