Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Illegal characters in path

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.

like image 209
Simon Avatar asked Mar 12 '23 00:03

Simon


1 Answers

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.

like image 58
Hans Kesting Avatar answered Mar 25 '23 08:03

Hans Kesting