Escaping directory chars in C# - 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..?

Related

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";

"Evaluate" a c# string

I am reading a C# source file.
When I encounter a string, I want to get it's value.
For instance, in the following example:
public class MyClass
{
public MyClass()
{
string fileName = "C:\\Temp\\A Weird\"FileName";
}
}
I would like to retrieve
C:\Temp\A Weird"FileName
Is there an existing procedure to do that?
Coding a solution with all the possible cases should be quite tricky (#, escape sequences. ...).
I am convinced such procedure exists...
I would like to have the dual function too (to inject a string into a C# source file)
Thanks in advance.
Philippe
P.S:
I gave an example with a filename, but I look for a solution working for all kinds of strings.
I'm pretty sure you can use CodeDOM to read a C# code file and parse its elements. It generates a code tree, and then you can look for nodes representing strings.
http://www.codeproject.com/Articles/2502/C-CodeDOM-parser
Other CodeDom parsers:
http://www.codeproject.com/Articles/14383/An-Expression-Parser-for-CodeDom
NRefactory: https://github.com/icsharpcode/NRefactory and http://www.codeproject.com/Articles/408663/Using-NRefactory-for-analyzing-Csharp-code
There is a way of extracting these strings using a regular expression:
("(\\"|[^"])*")
This particular one works on your simple example and gives the filename (complete with leading and trailing quote characters); whether it would work on more complex ones I can't easily tell unfortunately.
For clarity, (\\"|[^"]) matches any character apart from ", except where it has a leading \ character.
Just use ".*" Regex to match all string values, then remove trailing inverted commas and unescape it.
this will allow \" and "" characters inside your string
so both "C:\\Temp\\A Weird\"FileName" and "Hello ""World""" will match

System.ArgumentException: Illegal characters in path. error

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

How to escape "\" characters in Java

As we all know,we can use
string aa=#"E:\dev_workspace1\AccessCore\WebRoot\DataFile"
in c# in order not to double the '\'.
But how to do in java?
Unfortunately, there is no full-string escape operator in Java. You need to write the code as:
String aa = "E:\\dev_workspace1\\AccessCore\\WebRoot\\DataFile";
There is no whole string escape operator but, if it's for file access, you can use a forward slash:
String aa="E:/dev_workspace1/AccessCore/WebRoot/DataFile";
Windows allows both forward and backward slashes as a path separator. It won't work if you pass the path to an external program that mangles with it and fails, but that's pretty rare.
Might not be a direct answer to your question, but I feel this should be pointed out:
There's a system-dependent default name-separator character.
The really system-independent way is to do this:
String aa = "E:/dev_workspace1/AccessCore/WebRoot/DataFile";
String output = aa.replace('/', File.separatorChar);
It will give you
"E:\dev_workspace1\AccessCore\WebRoot\DataFile"
on Windows and
"E:/dev_workspace1/AccessCore/WebRoot/DataFile"
just about everywhere else.
If you write a path, you should use the '/' as path-separator under Java. The '/' is the official path-separator under Java and will be converted to the appropriate separator for the platform (\ under windows, / under unix). The rest of the string is unchanged if passed to the system, so the '\' also works under windows. But the correct way to represent this path is "E:/dev_workspace1/AccessCore/WebRoot/DataFile".
If you want to represent a '\' in a Java-String you have to escape it with another one: "This String contains a \".

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