I have string in which some xml resides.
The string is:
string xmlRead = "<ns0:RequestedAmount xmlns:ns0=\"http://tempuri.org/XMLSchema.xsd\"> <ns0:RequestedAmount></ns0:RequestedAmount> </ns0:RequestedAmount>" +
"<ns0:Response xmlns:ns0=\"http://tempuri.org/XMLSchema.xsd\"> <ns0:Response/> </ns0:Response>" +
"<ns0:isValid xmlns:ns0=\"http://tempuri.org/XMLSchema.xsd\"> <ns0:isValid/> </ns0:isValid>";
I have tried this:
string s=xmlRead.Replace(#"\","");
string s=xmlRead.Replace("\"","");
string s=xmlRead.Replace(#"\",string.Empty);
Nothing is working kindly help me out what I am doing wrong here.
Those backslashes won't actually appear in the final string. They are just escape sequences for the quotes "".
MSDN Escape Sequences
My guess is that you're viewing the string in the debugger which will still show them as unescaped.
Use following code this will help you.
string x=#"ABCD\EFG";
string y=x.Replace(#"\","");
Related
This question already has answers here:
Can I expand a string that contains C# literal expressions at runtime
(5 answers)
Closed 6 years ago.
I have a literal as a string in a file
def s_CalculatePartiallyUsedTechPenalty(rate):\n total = min(rate,0)\n title = \"Partially Used Technology Penalty\" \n return RateItem(title,total,FinancialUniqueCode.PartiallyUsedTechPenalty,False)
when reading the file the text obviously looks like this:
def s_CalculatePartiallyUsedTechPenalty(rate):\\n total = min(rate,0)\\n title = \\\"Partially Used Technology Penalty\\\" \\n return RateItem(title,total,FinancialUniqueCode.PartiallyUsedTechPenalty,False)
Is there clean way to convert this string so that the value in the file is also the actual value of the string in code. In other words that that \n for example is \n and not \\n.
I understand that I can write a method that goes and replaces all the applicable values, but I do not want to do that unless it is the only way.
Edit: In response to John Wu's answer. No I am not confused. I do understand exactly that this is happening however I want to convert the literal value "\n" to the newline character. So instead of the literal value of \n it should be a new line.
Basically the inverse of How to convert a string containing escape characters to a string
You are confusing yourself. The string held in the file will be exactly the same as the string held in a string variable obtained by reading the file.
Perhaps you are using Visual Studio to inspect the string (i.e. using the Watch window or just hovering over the variable while the code is in debug mode). In this case, Visual Studio will display the extra slash to indicate that the string variable contains the literal value "\n" instead of a newline character.
If you want to eliminate the escape characters in the Watch window, you can append the format specifier ,nq to the variable name (link).
See also this question on StackOverflow.
If you can not fix file-writing code, that you can solve this issues in a following way:
String.Replace(#"\\\", #"\");
String.Replace(#"\\", #"\");
Or, in case, if you normal unescaped string,
String.Replace(#"\\\""", "\"");
String.Replace(#"\\n", Environment.NewLine);
P.s. Also think about other special characters, like \t
UPDATED:
Even better approach:
class Program
{
static void Main(string[] args)
{
var escaped = #"def s_CalculatePartiallyUsedTechPenalty(rate):\n total = min(rate,0)\n title = \""Partially Used Technology Penalty\"" \n return RateItem(title,total,FinancialUniqueCode.PartiallyUsedTechPenalty,False)";
var unescaped = Regex.Unescape(escaped);
Console.WriteLine(unescaped);
}
}
I've got a bit of a weird one here (well I think that it's weird!).
I'm using a web service to return a string and I'm trying to put quotes inside the string so say for instance I want to return the string Craig says, "hello" I would normally do something like:
zString = "Craig says, \"Hello\"";
but what I'm actually getting back from the webservice is the string including the \'s. So I actually get back:
Craig says, \"Hello\"
This is driving me loopy! Any ideas anyone? Could this declaration at the start be causing the problem?
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
Thanks,
Craig
That a json string inside an json output, so you need to parse it twice.
RFC 4627:
All Unicode characters may be placed within the
quotation marks except for the characters that must be escaped:
quotation mark, reverse solidus, and the control characters (U+0000
through U+001F).
This simply means that nothing is wrong. The character is being escaped according to the json standard.
Yes. Being in JSON format, it also escapes the " characters by using \ when returned.
It's the same as:
{
"zString": "Craig says, \"Hello\""
}
In my project, I need to read some URLs and store the starting tags into some variables, but the project won't compile. May be, its because I am not using the assignment to the string correctly. Following is what i tried and got the compile error
string startTag = "<span id="productLayoutForm:OurPrice" class="pdp_details_hs18Price" itemprop="price">";
string anotherStartTag = "<span class="price final-price our fksk-our" id="fk-mprod-our-id">Rs.<span class="small-font">"
Please tell, what should be the correct code for above and where can I learn how to store such HTMLs into string or how to use string for such puposes.
You need to "escape" the quotes in your strings, for example:
string startTag = "<span id=\"productLayoutForm:OurPrice\" class=\"pdp_details_hs18Price\" itemprop=\"price\">";
The \ before the quotes that are inside the string tells the C# compiler that the quotes are part of the string and not the beginning/end of the string.
The " sign indicates the start and end of a string.so to use it in the middle of a string you have to escape it, do that by setting a backslash in front of it.. Like this: \"
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..?
So I'm trying to create a path in C#. I use Environment.Machinename and store it a variable serverName. Then I create another string variable and have some other path extension in there. Here is my code so far:
string serverName = Environment.MachineName;
string folderName = "\\AlarmLogger";
No matter what I do I can't seem to obtain only one backslash prior to AlarmLogger. Any ideas how I can specify a path in C#?
Edit: I'm wondering if my code doesn't seem to want to paste correctly. Anyways when i paste it I only see one backslash but my code has two. Because of the escape character sequence. But something like
string test = #"\\" + serverName + folderName
doesn't seem to want to work for me.
Use Path.Combine(serverName, folderName). Path.Combine is always a better solution than concating it on your own.
You cannot use Path.Combine for this as suggested. The reason is that it ignores static variables if the first entry is static, e.g. Environment.MachineName (see MSDN docs for details). If you use Path.Combine(servername, foldername) you will get "\AlarmLogger". Plus, it parses double slashs to single slashes.
That being said, you can do something like the following (among other ways):
string serverName = Environment.MachineName;
string folderName = "\\\\AlarmLogger"; //this gives alarmlogger two leading slashes
string test = #"\\" + serverName + folderName.Substring(1,folderName.Length-1); //this removes one of the two leading slashes
You could use a slew of ways to remove the leading slash besides substring.
It's not clear what you are trying to do or what is going wrong.
If you are having trouble including backslashes in your strings, they need to be escaped with an extra backslash:
string twoBackslashes = "\\\\";
Or you can do it like this:
string twoBackslashes = #"\\";
If you are trying to manipulate paths, look at the System.IO.Path class. In particular, Path.Combine can be useful.