I am trying to get to a file located in
C:\Program Files (x86)\test software\myapp\demo.exe
In VS debugger i see the path as:
"\"C:\\\Program Files (x86)\\\test software\\\myapp\\\demo.exe\""
when i print it out i see in console :
"C:\Program Files (x86)\test software\myapp\demo.exe"
but when i try something like
FileInfo fi = new FileInfo(PathMentionedAbove);
i get Illegal character in path.
What is wrong? the file exists and path is correct. what's illegal above this path?
any help would be appreciated.
Your path includes " at the beginning and at the end. Drop the quotes, and it'll be ok.
The \" at the beginning and end of what you see in VS Debugger is what tells us that the quotes are literally in the string.
Try this:
string path = #"C:\Program Files (x86)\test software\myapp\demo.exe";
You seem to have the quote marks (") embedded in your string at the start and the end. These are not needed and are illegal characters in a path. How are you initializing the string with the path?
This can be seen from the debugger visualizer, as the string starts with "\" and ends with \"", it shows that the quotes are part of the string, when they shouldn't be.
You can do two thing - a regular escaped string (using \) or a verbatim string literal (that starts with a #):
string str = "C:\\Program Files (x86)\\test software\\myapp\\demo.exe";
Or:
string verbatim = #"C:\Program Files (x86)\test software\myapp\demo.exe";
The string is surrounded by double quotes. Yes, that's not a valid character in a path.
You should probably tackle it at the source, but you can strip them out with:
path = path.Replace("\"", "");
I usualy would enter the path like this ....
FileInfo fi = new FileInfo(#"C:\Program Files (x86)\test software\myapp\demo.exe");
Did you register the # at the beginning of the string? ;-)
try
"C:/Program Files (x86)/test software/myapp/demo.exe"
Related
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.
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.
Path.GetInvalidFileNameChars
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;
I have the problem with whitespaces in my console application. My application is crashing because of not allowed chararcters.
My application is expecting an argument which is a path of the filesystem. So it will be called like this
myProg.exe "D:\tmp\with whitespace\"
With that information I want to create a file in the given folder, but this is not possible because of not allowed char.
String pdfName = "foobar.pdf
String datapath = args[0];
String targetJobFile = datapath + pdfName + ".txt";
I can see in the debugger that the targetJobFile value is
"D:\tmp\with whitespace\"foobar.pdf.txt
And there i receive the exception.
Thanks
You need to remove the quotes from the argument, so before using it, use Trim:
String realArg = args[0].Trim('"');
You already have the \ that Path.Combine would give you; but if you don't want your users to have to enter it, using Path.Combine is a good way to get the path separator character into your string.
Why not just check for existence of " character and replace them before making the full path like
datapath = datapath.Replace("\"","");
String targetJobFile = datapath + pdfName;
You can go one step ahead and use Path.GetInvalidPathChars() which will return all invalid characters not allowed in path names and remove it from your path as follows -
modifiedPathName = new Regex(string.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidPathChars())))).Replace(PathName, replaceChar);
Hey guys I have this piece of code that will first store a path in a variable, check if that path exists, if not create it. then take that path and add my file name to it.
Here is the code
appData = string.Format("{0}{1}\"", controller.Server.MapPath("~/App_Data/"), Guid.NewGuid().ToString());
if (!Directory.Exists(appData))
Directory.CreateDirectory(appData);
filePath = string.Format("{0}\"{1}", appData, model.File.FileName);
model.File.SaveAs(filePath);
data.Add("attachment", filePath);
But when it gets to the SaveAs function it states
Illegal character in path
AppDath = C:\Users\Ben\Documents\Team Foundation Server\Team
Projects\Shared\Orchard
1.6\Orchard\src\Orchard.Web\App_Data\392216b5-32ad-41f4-82bf-e074b13f25df\"
Any idea why?
use Path.Combine
filePath = Path.Combine(appData, model.File.FileName);
same to create appData path
appData = Path.Combine(controller.Server.MapPath("~/App_Data"), Guid.NewGuid().ToString());
Use
filePath = string.Format(#"{0}\"{1}", appData, model.File.FileName);
The # char show the compiler that the string doesn't have any backslashed characters.
Normaly, you use the \ prefix in some special chars, like \n means a newline. You string has a \, so the compiler tries to resolve it with the next char in the string.
Another way is to escape the backslash with the second one, like this:
filePath = string.Format(#"{0}\\"{1}", appData, model.File.FileName);
string slink = "\\README.TXT";
string ipath = "C:\\Users\\Crystal\\Documents\\Visual Studio 2010\\Projects\\workspace\\workspace\\bin\\Debug";
string test = lpath+"\\workspace\\"+slink;
string test1 = "C:\\Users\\Crystal\\Documents\\Visual Studio 2010\\Projects\\workspace\\workspace\\bin\\Debug\\workspace\\README.TXT";
string ftpfullpath = myUri.ToString();
WebClient request = new WebClient();
FileStream file = File.Create(#test);
if i write FileStream file = File.Create(#test); i get error illegal characters.
if i write FileStream file = File.Create(#test1); it works!
i think something is wrong with gluing multiple string path values. i've tried also Path.Combine but also doesn't work
In your third line of code, you've used lpath instead of ipath - i am assuming that's a typo
Use this:
string resultPath= Path.Combine(p1, p2);
MSDN Reference
Taking it that lpath is a typo for ipath, the latter adds an extra slash (or set of slashes, depending on the context) before README.TXT.
That is to say,
\\workspace\\README.TXT
becomes,
\\workspace\\\\README.TXT
You're writing "..\\" + "\\...".
A path cannot have two consecutive \s.
The problem is your either your slink or your test. The code you have ends up with the following path:
C:\Users\Crystal\Documents\Visual Studio 2010\Projects\workspace\workspace\bin\Debug\workspace\\README.TXT
Notice the double slash before README.TXT?
This is caused because slink becomes:
\README.TXT
Then you are trying to combine that with:
C:\Users\Crystal\Documents\Visual Studio 2010\Projects\workspace\workspace\bin\Debug\workspace\
You can do 1 of 2 things to fix the problem:
Remove the \\ from the slink
Remove the trailing \\ from the "\\workspace\\" when you try to combine them
I would suggest option 1 - it clearly separates the filename from the path of the file. Having the \\ preceding the file implies that the filename also has its path info
string targetPath = #"C:\Program Files\saadhvi\SetupSafetyPADUniversal\";
string createDatabasesScriptFilePath = Path.Combine(targetPath, "\\EADBScripts\\CreateDatabases.sql");
i am getting the value of createDatabasesScriptFilePath is \EADBScripts\CreateDatabases.sql
but i expected it would be C:\Program Files\saadhvi\SetupSafetyPADUniversal\EADBScripts\CreateDatabases.sql
what is the wrong with my code?
Here is why your code is returning the 2nd path (copied from MSDN help) -
If path2 does not include a root (for example, if path2 does not start with a separator character or a drive specification), the result is a concatenation of the two paths, with an intervening separator character. If path2 includes a root, path2 is returned.
Remove the first \ from the string "\EADBScripts\CreateDatabases.sql"
I'm not completely sure of the reason, but a I guess Path.Combine wants as second parameter a relative path, and a relative Path does not start with a \.
Remove the initial backslash from "\EADBScripts..." in the second argument.
string targetPath = #"C:\Program Files\saadhvi\SetupSafetyPADUniversal\";
string createDatabasesScriptFilePath;
createDatabasesScriptFilePath= Path.Combine(targetPath, "EADBScripts\\CreateDatabases.sql");