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.
26 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.
FilePath = string.Concat(FilePath.Split(System.IO.Path.GetInvalidFileNameChars())).Trim(); Well you can replace blank space with %20 character and while retrieving replace back with blank space again like (you may as well choose to use regular expression for the same)
String Filepath = @"C:\Temp\My Excel File.xls"; Filepath = Filepath.Replace(" ", "%20"); While retrieving back
string mypath = pathyouhavegotfromDB.Replace("%20", " "); I think you need to put quotation marks around the path with spaces.
string filepath = @"C:\Temp\My Excel File.xls"; filepath = $"\"{filepath}\""; Thanks for everyone's help, I tried all of these and unfortunately they didn't work which led me to believe that the issue wasn't what I originally thought.
It turns out that the files causing the Illegal characters in path all had carriage return characters at the end of the file name, after the file extension.
To resolve this I used the following code and now it works perfectly
FilePath = FilePath.TrimEnd('\r', '\n'); Thanks everyone for your help.
Try this:
String StringCorrectedFilePath = @""+ Filepath;