the text I've got from the file has the following string: 1"-DC-19082-A3
after getting that line I get the following string (got it while debugging): "\"1\"\"-DC-19082-A3\""
as I'm searching on the DB it's not of any use like that
any idea how can I get back to the original?
I've seen that StreamWriter.WriteLine would do the job, but I don't want to create any file for this.
I tried the following, but it didn't work
StringBuilder sb = new StringBuilder();
sb.Append(#"\");
sb.Append('"');
string strToReplace = sb.ToString();
string lineNumberToSearchFor = lineNumber.Replace(strToReplace, string.Empty);
hopefully there's an easy way of achieving this
many thanks!
It adds the backslashes to indicate quotes in the middle of the string. The backslashes aren't actually there, the quotes are.
If you want to remove the quotes instead:
myString.Replace("\"", string.Empty);
The backslashes are added by the Watch window.
The string itself doesn't have backslashes.
Related
I have a path that is named defaultPath I want to add it into this verbatim string literal but can quite get the quotes around it.
#"""C:\Mavro\MavBridge\Server\MavBridgeService.exe"" /service /data ""..\Data"""
I was trying to add +defaultPath to replace Data. So lets say I have a folder name Data.Apple I want the output to be
"C:\Mavro\MavBridge\Server\MavBridgeService.exe" /service /data "..\Data.Apple"
But when I have been doing it for the past half hour I have been getting
"C:\Mavro\MavBridge\Server\MavBridgeService.exe" /service /data "..\"Data.Apple
or
"C:\Mavro\MavBridge\Server\MavBridgeService.exe" /service /data "..\" + defaultPath
Do it like this (preferred):
string.Format(#"""C:\Mavro\MavBridge\Server\MavBridgeService.exe"" /service /data ""..\{0}""", defaultPath);
Or like this:
#"""C:\Mavro\MavBridge\Server\MavBridgeService.exe"" /service /data ""..\" + defaultPath + "\"";
The first one uses string.Format, which basically replaces the {0} in the first parameter with the value in the second parameter and returns the result.
The second one uses classical string concatenation and what I did there was to remove the double quotes after the last backslash (""..\ instead of ""..\""), because you didn't want the quotes after the backslash. You wanted the quotes after defaultPath. And that's what this code does: It appends defaultPath (" + defaultPath) and appends the closing quote afterwards (+ "\"").
So if you would like to take advantage of the string interpolation with c# 6 you could also do
var randomText = "insert something";
var yourString = $#"A bunch of text in here
that is on seperate lines
but you want to {randomText }";
Use string.Format to insert the variable between the quotes:
string path = "Data.Apple";
string verbatim = string.Format(#"""C:\Mavro\MavBridge\Server\MavBridgeService.exe"" /service /data ""{0}""", path);
MessageBox.Show(verbatim);
It makes it easier to read and to implement, you can replace other portions of the path with variable sections in a similar manner.
If you try to just append the "defaultPath" variable to the end, it will never work correctly, as you've already added the closing ".
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..?
i need a regex in c# that will escape double quotes inside string literal. so if i have this string: "How about "this" and how about "that"". i will be able to use it in javascript without errors. because i am writing this literal to the page as js var.
EDIT: i will try to explain more about the problem.
i writing messege to the page like this:
string UserMsg = GetMessageText(999);
StringBuilder script = new StringBuilder();
script.AppendFormat("var UserMsg =\"{0}\";{1}", UserMsg, Environment.NewLine);
ScriptManager.RegisterClientScriptBlock(this, GetType(), "scriptparams", script.ToString(),true);
now lets say messege 999 is this: "we found a "problem" in your details".
this is causing js errors.
You should not use regular expressions to escape your C# strings into a JavaScript friendly / safe format. Instead, assuming you are using .NET 4, you can use HttpUtility.JavaScriptStringEncode and it's overload to take care of both single and double quotes for you.
For example:
string UserMsg = GetMessageText(999);
StringBuilder script = new StringBuilder();
script.AppendFormat("var UserMsg =\"{0}\";{1}", HttpUtility.JavaScriptStringEncode(UserMsg), Environment.NewLine);
ScriptManager.RegisterClientScriptBlock(this, GetType(), "scriptparams", script.ToString(),true);
Would ouput the following with UserMsgset to "we found a "problem" in your details":
var UserMsg ="we found a \"problem\" in your details";
Assuming I understand you correctly, to escape a " in C# source code, you can do it like this:
"\""
or
#""""
Either of those literals defines a string containing single double quote character.
On the other hand perhaps you need to know how to escape the quote character in Javascript. That is done with \". You can use String.Replace() to effect that but you would be much better off with a proper HTML/JS emitter library.
See the Web Protection Library (also known as AntiXSS). That has a JavascriptEncode method to do this and other escapes.
Here is my suggestion for you:
var regex = new Regex("\"");
var result = regex.Replace(stringToReplace, "\\\"");
I believe something like this may work:
Regex.Replace(myString,'"',"");
I think your question has been answered already but if you still need the complete code.
below piece of javascript would work for you.
var s = "this is \"Hi \" ";
alert(s);
Praveen
Thanks to NgM I am using StringBuilder in .NET 3.5 to find and escape special chars. However, when I use the ToString method, it escapes the escape chars which then makes the previous exercise useless. Anyone know how to get around that?
Here is the code:
private String ParseAndEscapeSpecialChars(String input)
{
StringBuilder sBuilder = new StringBuilder(input);
String output;
String specialChars = #"([-\]\[<>\?\*\\\""/\|\~\(\)\#/=><+\%&\^\'])";
Regex expression = new Regex(specialChars);
if (expression.IsMatch(input))
{
sBuilder.Replace(#"\", #"\\");
sBuilder.Replace(#"'", #"\'");
}
output = sBuilder.ToString();
return output;
}
Here are the results from debug:
input "005 - SomeCompany's/OtherCompany's Support Center"
sBuilder {005 - SomeCompany\'s/OtherCompany\'s Support Center}
output "005 - SomeCompany\\'s/OtherCompany\\'s Support Center"
StringBuilder doesn't escape characters. It does nothing special or clever. Dollars to doughnuts you're just seeing this in the debugger, which does show you an escaped version.
You say your results are from debug. If by that you mean the debugger itself, by examining the string contents by hovering over the variable or putting it on a watch list in VS then the debugger display will escape the slashes in its windows/tooltips. However if you actually output the string in your code you will see the escaping is not there - it's just a debugger "feature".
Try
System.Diagnostics.Debug.Writeline(myOutputVariable);
and look in the output window to see the "real" contents.