System.ArgumentException: Illegal characters in path. error - c#

I`m getting an ArgumentException from the following code:
string strPath="C:\somename.xls";
startPath=System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
filePath = System.IO.Path.Combine(startPath, strPath);
I found this code on Stack Overflow.
Link:
C#:Copy protected worksheet to another excel file
I don't exactly know what it is. Please tell me what it is. This code I'm building into an exe.
Lastly, I need to Copy one worksheet to another file.
What`s wrong am I doing? I deploy this in server.

what that code appears to do, is it gets your working directory(wherever the exe associated with your code is), and combines it with "C:\\somename.xls"(which doesn't make sense.)
I think you might have intended something like
string strPath=#"somename.xls";
so assume you're running your application from
"C:\Users\owner\documents\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug"
what that code would do is set filePath to
"C:\Users\owner\documents\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\somename.xls"
the first thing I saw was
string filePath="C:\somename.xls";
\ is a special character, for determining other characters. for instance '\n' is a newline. '\\' is the actual backslash.
so, you want to escape your \ with another \
string filePath="C:\\somename.xls";
or make it a literal string by putting a # in front of it.
string filePath=#"C:\somename.xls";

Your code should be:
string filePath = "C:\\somename.xls"
You need double backslashes.

Two problems with the code,
First
string filePath="C:\somename.xls";
\ is a special character, for determining other characters. for instance '\n' is a newline. '\\' is the actual backslash.
Second
filePath contains a root path, C:\\. Path.Combine will just return filePath then, it cannot be combined.

Your main problem is in startPath parameter.
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
If you trace your code, in FileName you will see a bad symbol character witch is illegal

Related

C# automatically substitutes forward-slash with back-slash in path...why?

I have a textbox where I put the name of a file that contains the forward-slash character '/'
When I grab the text from the textbox the '/' is automatically replaced with '\' and it obviously can't find the file, for example:
I write C:\Users\Temp\my/file.txt
I get C:\Users\Temp\my\file.txt
So, instead of opening "my/file.txt", it searches for a directory "my" which contains "file.txt"
How can I solve this?
If you're using Windows (which I assume you are, given the paths in your example), then / is an invalid character for a filename:
The easiest solution here would be to remove the slash from the filename as this is likely to cause further issues down the line.

Using The # symbol for a Directory so two backslashes aren't needed

this seems very simple but upon research I cannot find out how to use the # sign in a directory to prevent it from having to be to backslashes.
An example is of
DirectoryInfo folderInfo = new DirectoryInfo(#"C:\");
But In my Application The directory will be dynamic so I cannot do this:
DirectoryInfo folderInfo = new DirectoryInfo(#Globals.directoryRoute);
So I was wondering what is the correct way to put the # symbol before the string.
Globals.directoryRoute is set as C:\ but the user can change this input so I was hoping instead of having to parse out every double backslash I can use this to make it so only one backslash is needed.
Would this be an effective way of doing it or should I just parse out every second backslash?
The # prefix is a tool to tell the compiler to not take the backslash as an escape character within the following string. If the string is entered at runtime, you don't need to worry about that. So you can just use the content of Globals.directoryRoute as it is.
The double backslashes are only needed for string literals in your code. In memory, only a single backslash is stored in the string, so no # symbol is needed when dealing with strings that are already in memory. Similarly, user input does not need the double backslashes, since it is not interpreted in the same manner as source code. For instance, if you have a text box called txtPath, the user can simply type C:\some\path, not C:\\some\\path as you would normally need to do in source code. When you read the value of that text box in code, you can just use:
string path = txtPath.Text;
This will be the same as if you had the following code:
string path = #"C:\some\path";
or, equivalently:
string path = "C:\\some\\path";

Passing filepath into Main(string[] args) not working

I am trying to pass a file path into a C# Console Application but am having problems with the string being incorrect by the time it reaches the console application.
If I run my application from the command line, with a file path parameter:
MyApp "C:\Users\DevDave\Documents\Visual Studio 2012\Projects\MyProject\"
A windows dialogue pops up and informs me that my application has stopped working, and when I click the Debug option, I can see that the result of args[0] is:
C:\Users\DevDave\Documents\Visual Studio 2012\Projects\MyProject"
Note there is still a trailing quote at the end.
If I pass a second argument:
MyApp "C:\Users\DevDave\Documents\Visual Studio 2012\Projects\MyProject\" "any old string"
I get an error again, and after viewing in debug I see that args[0] is:
C:\Users\DevDave\Documents\Visual Studio 2012\Projects\MyProject" any
I am baffled as to why this is happening. My only guess is that the backslashes in the string are causing some kind of escape sequence from the string? Edit: I notice that the same is happening in the string example above! It seems \" is causing problems here.
I just want to pass in the file path of the current solution directory and am calling my app from a pre-build event using $(SolutionDir), and know that I can get the path of the current solution in other ways. But this is simplest and I am curious as to why it does not work as expected.
Yes, the rules for commandline arguments are a little murky.
The \ is the escape char and you can use it to escape quotes ("). You'll have to escape a backslash but only when it is preceding a quote. So use (note the '\\' at the end):
MyApp "C:\Users\DevDave\Documents\Visual Studio 2012\Projects\MyProject\\"
or, simpler but you'll have to deal with it in C# somehow:
MyApp "C:\Users\DevDave\Documents\Visual Studio 2012\Projects\MyProject"
Also see this question
That's why it's always better to use / in path
"C:/Users/DevDave/Documents/Visual Studio 2012/Projects/MyProject/" "any old string"
take a look: http://en.wikipedia.org/wiki/Path_(computing) , you can use both \ and / in path but if you want any shell compatibility I suggest to use /
Anything that comes after MyApp will be the first argument (args[0]). In your case, the first argument is "C:\Users\DevDave\Documents\Visual Studio 2012\Projects\MyProject\". Also, the quote at the end of the string seems to happen because \" means that you want to want to escape the quote and write it as a string. In this case, the quote is not closing the string. That is the reason that your args[0] is the whole thing that comes after MyApp
If you don't want to scape the quote and have a slash behind it, you should do \\"
You could try this and tell me what happens:
MyApp "C:\Users\DevDave\Documents\Visual Studio 2012\Projects\MyProject\\"
(look at the double slash)
Hope it helps.
Continuation of Henk's answer, and choose to add a \ at the end of the path, then:
If you choose to hack the bug by choosing this code in Henk's answer ("simpler but you'll have to deal with it in C# somehow:"), then you should realize some bugs that will occur:
args[0] will only be set, even if you pass multiple parameters in. The length of args will be equal to 1. So you have to split args[0] into multiple pieces for your hack.
You have to replace any " characters with a \ if they are at the end of the pieces you split.

Escaping directory chars in C#

I need to escape chars in a string I have, which content is C:\\blablabla\blabla\\bla\\SQL.exe to C:\blablabla\blabla\bla\SQL.exe so I could throw a process based on this SQL.exe file.
I tried with Mystring.Replace("\\", #"\"); and Mystring.Replace(#"\\", #"\"); but none worked.
How could I do this?
EDITED: Corrected type in string.
I very strongly suspect that you are looking this input string in the Visual Studio debugger and fooling yourself that there are actually 2 \ whereas in reality there aren't. That's the reason why attempting to replace \\ with \ doesn't do anything because in the original string there is no occurrence of \\. And since you are looking the output once again in the debugger, you are once again fooling yourself that there are 2 \.
Visual Studio debugger has this tendency to escape strings. Log it to a file or print to the console and you will see that there is a single \ in your input string and you don't need to replace anything.
It looks like you're trying to replace double backslash (#"\\") in a string with single backslash (#"\"). If so try the following
Mystring = Mystring.Replace(#"\\", #"\");
Note: Are you sure that the string even contains double backslashes? Certain environments will print out a single backslash as a double (debugger for example). Your comment mentioned my approach didn't work. That's a flag that there's not actually a double backslash in your string (else it would work).
The # character specifies a string as a verbatim literal string, but that is when constructing a string. If you use Mystring.Replace("\\", #"\") then nothing will be replaced, essentially, as the two strings are the same.
If you want a string without the escape characters, then either define it with:
string path = #"C:\Some\Directory\And\File.txt";
Or you can replace the \\ with / like so:
path = path.Replace('\\', '/');
It is worth noting, as mentioned by Darin Dimitrov, that the string containing two \ characters is likely just the display of the string (i.e. when using the debugger) and not the actual value of the string.
i think OP is asking how to escape \\ in File Path, if that in the case, as OP is not mentioning where he's trying to use this. so i'm putting a guess.
Then You use Path.Combine() method to get the FileName path.
Path.Combine() Documentation
where are you looking at this output? because it could be the string is what you expect, but viewing the value through the debugger, output window, etc. is escaping the slash
Use something like:
myStr = myStr.Replace(#"\\", #"\");
Make sure you assign the result of Replace method to myStr. Otherwise it goes into void ;)
Try adding "|DataDirectory|\MyFile.xyz" where you need it. It works with connection strings it might work with something else (I haven't really tried to apply it to something else).
I didn't understand what you want, if you just want do get the file name (escape directory chars) you can try:
string fileName = Path.GetFileName(YourString)
Noloman.... when you concatenate are you perhaps missing a "\" when concatenating the directory.. I am assuming that you are trying to join directory + some sub directory.. #noloman keep in mind that in C# "c:\Temp" is written like this "c:\Temp" or #"c:\Temp" one is Literal the other is how to represent a "\" in the legacy way of coding because the "\" is an escape Char and when dealing with directorys we represent all paths and sub paths with "\"
so perhaps by you replacing the "\" you are truly messing up your own expected process
Mystring = Mystring.Replace(#"\\", #"\");
should work for you unless you are truly meaning to do
Mystring = Mystring.Replace(#"\", "\"); which if you believe that you are expecting a "\" to be used to build the directory.. then of course it will not work.. because you have just in essense replaced the backslash with a return char.. I hope that this makes sense to you..
System.IO.Directory.GetCurrentDirectory(); you are using is also an Issue.. SQL Server is not that application thats running the code.. it's your .NET application so you need to either put the location of the SQL Server into a variable, app.config, web.config ect... please edit your question and paste the code that you are using to do what it is that you want to do inregards to the SQL Server Code.. you would probably want to look at the Are you wanting to do something like Process.Start(....) meaning the file name..?

How to return a verbatim string from ConfigurationManager.AppSetting["settingname"].ToString()

I am using the ConfigurationManager.AppSetting["blah"].ToString() method to get the path to the folder that contains the files I'm needing. But I'm throwing an UnsupportedFormatException on the path when it tries to use Directory.GetFiles(path).
The returning value has the escape characters included and I'm not sure how to keep it from returning the extra characters. This is what the path looks like after it is returned:
\\\\\\\\C:\\\\folder1\\\\folder2
I needed to remove the first four "\" to give it a correct path.
you have extra back-slash \ at the beginning of your path.
try putting "C:\folder1\folder2" instead of "\\C:\folder1\folder2" in your config file, and it will work.

Categories