I have a xml string shown below:
String xml = #"<axislable='ihgyh\nuijh\nkjjfgj'>";
Now when I try to output the xml it shows <axislable='ihgyh\nuijh\nkjjfgj'>
But my requirement is to break the line like below
<axislable='ihgyh
uijh
kjjfgj'>
I have tried replacing the xml using xml = xml.Replace("\n", "\\n"); But it doesnt seems to work.Any ideas how to break the line?
Regards,
Sharmila
Don't use the # prefix:
var xml = "<axislable='ihgyh\nuijh\nkjjfgj'>";
Also you may need "\r\n" instead:
var xml = "<axislable='ihgyh\r\nuijh\r\nkjjfgj'>";
It's not working since you have no line breaks in your string. Your string contains the substring "\n".
Notice you use the # operator.
Try the following:
xml = xml.Replace("\\n", "\n");
Try
xml.Replace(#"\n", Envioroment.NewLine);
Similar to Leo's answer (sorry don't know how to comment on your answer)
String xml = String.Format("<axislable='ihgyh{0}uijh{0}kjjfgj'>", Environment.NewLine);
The # character means that the string is a verbatim string, meaning that escape characters like \n in the string are not processed and treated as text.
The following string is a regular string:
string xml="<axislable='ihgyh\nuijh\nkjjfgj'>";
and translates the \n escape sequence to a newline as you would expect.
You should check the documentation on string literals for the difference between the two forms.
Related
In order to be able to read a file in asp.net, the file path must be written in this:
1.
C:\\yung\\Desktop
returns
however, the string that the fileUpload get returns is
2.
C:\yung\Desktop
After reading the comments i have this code:
string FilePath = FileUploadPublicInfo.PostedFile.FileName;
System.IO.StreamReader file = new System.IO.StreamReader(FilePath);
string line = File.ReadLines(FilePath.ToString()).Skip(4).ToString();
TextBox1.Text = line.ToString();
But now its giving this error:
System.Linq.Enumerable+<SkipIterator>d__30`1[System.String]
How to solve this problem?
Thank you.
I'm not so sure I understand the question, but I think you are looking for string.Replace:
string DoubleSlash(string singleSlash)
{
return singleSlash.Replace(#"\", #"\\");
}
The reason backslashes disappear is that C# compiler treats slashes in string literals as a special "escape" character. Because of this treatment, backslash needs to be encoded as two slashes in a regular string literal.
C# offers two ways of inserting backslashes the way you need:
Use verbatim literals - prefix it with "at" sign, i.e. #"C:\\yung\\Desktop", or
Double each slash - put two slashes for each slash in the result: C:\\\\yung\\\\Desktop
Ok, i have manage to solve this problem, turns out it was not reading anything.
This is the code that i finally get:
This is to retrieve the File's path, using this, would give the file path will double slash, so there is not a need for Replace(#"\",#"\")
string FilePath = FileUploadPublicInfo.PostedFile.FileName;
Then read the specified file
System.IO.StreamReader file = new System.IO.StreamReader(FilePath);
If you know which line you specifically want, this retrieves the 5th line
string line = File.ReadLines(FilePath.ToString()).Skip(4).First().ToString();
Thank you so much for your help...
I need to send the value I receive from the model with this link, the proposalName field must be in quotes.How can I do it?
Here is my service url.
string path = string.Format("{ProposalId:{proposalId},ProposalName:{"proposalName"},VendorId:{vendorId}}",
Uri.EscapeDataString(proposalId.ToString()),
Uri.EscapeDataString(proposalName),
Uri.EscapeDataString(vendorId.ToString()));
You can simply put quotes around by escaping the quotes, like this -
string path = string.Format("{{0},ProposalName:\"{1}\",VendorId:{2}}",
Uri.EscapeDataString(proposalId.ToString()),
Uri.EscapeDataString(proposalName),
Uri.EscapeDataString(vendorId.ToString()));
As per your updated question, if you need to pass double quotes in URL, you need to encode it to %22
You can also use URI which allows a lot of flexibility with urls. For example -
Uri myUri = new Uri("http://google.com/search?hl=en&q=\"query with quotes\"");
Going with your example - Replace EscapeDataString with Uri.EscapeUriString. It will escape the chracter to form a valid URL. " will get replaced by %22
Some suggestions here and here-
Your problem exactlly in the {"1"} part. The double quotation mark " should be outside the {}, not inside them.
here is the fixed code.
string path = string.Format("{{0},ProposalName:\"{1}\",VendorId:{2}}",
Uri.EscapeDataString(proposalId.ToString()),
Uri.EscapeDataString(proposalName),
Uri.EscapeDataString(vendorId.ToString()));
or
string path = string.Format(#"{{0},ProposalName:""{1}"",VendorId:{2}}",
Uri.EscapeDataString(proposalId.ToString()),
Uri.EscapeDataString(proposalName),
Uri.EscapeDataString(vendorId.ToString()));
and if you are using C# 6 then you can write it as following
string path = $"{Uri.EscapeDataString(proposalId.ToString())},ProposalName:\"{Uri.EscapeDataString(proposalName)}\",VendorId:{Uri.EscapeDataString(vendorId.ToString())}";
This might do the trick for you
\"{1}\"
instead of
{"1"}
because you can put \ symbol to indicate escape sequence followed by a reserved characters
So
string.Format("{{{0},ProposalName:\"{1}\",VendorId:{2}}}",
I think escaping the quotes and placing them outside the brackets will work:
"{{0},ProposalName:\"{1}\",VendorId:{2}}"
Depending on the C# version, you can also do it like this, which I often think is an easier and cleaner way to do it:
string path = $"{proposalId},ProposalName:\"{proposalName}\",VendorId:{vendorId}";
You have two problems:
Wrong quotation (should be outside the braces {...} and escaped)
Incorrect { and } escape: {{ means just a single '{' in a formatting string
Should be
string path = string.Format("{{{0},ProposalName:\"{1}\",VendorId:{2}}}",
please, notice
escaped quotations \" which are outside {1}
tripled curly braces{{{ and }}}
Edit: in your edited question you have the same errors:
string format =
"http://mobile.teklifdosyam.com/VendorReport/GetListProposalService?&page=1&start=0&limit=10&filter=" +
"{{ProposalId:{0},ProposalName:\"{1}\",VendorId:{2}}}";
string path = string.Format(format,
Uri.EscapeDataString(proposalId.ToString()),
Uri.EscapeDataString(proposalName),
Uri.EscapeDataString(vendorId.ToString()));
please, notice escaped quotations \" which are outside the {1}, double '{{' and tripled '}}}'. When formatting you have to use numbers as place holders: so {"proposalName"} must be changed into {0}
I want find and replace a substring in a string in C#.
The substring I want to find looks like this:
],\"
and the substring i want to replace looks like this ],\"Name
This is what i tried so far:
string find = #"],\""";
string replace = #"],\""Name";
string newjson = jsonstring.Replace( find, replace );
From your comment
Debugger show me like this "],\\\"Name"
That is the correct output, the debugger is showing you the escaped version of your string. the \\ turns in to a single \ and the \" turns in to a " once the escaping has been applied.
If you click the magnifying glass in the box in your debugger it will open a new window with the escaping applied.
Are you getting any errors when doing what you did?
Otherwise try without using a literal "#"
so something like this:
string find = "],\\\"";
string replace = "],\\\"Name";
string newjson = jsonstring.Replace(find, replace);
Sometime double quotes and string literals still give me issues so I do it that way without using the literal. Hope that helps.
How can I remove the black diamond question mark when I read a text file?
In the text file the real character is • but after reading the text file it became �. I don't know how to manipulate/delete that character.
This character means, that you are reading the file in the wrong encoding. At first you need to know how your file is encoded. You could get this informatio from Notepad++ for example. Then in your code read the file with this encoding specified. Here is an example to read unicode files:
var text = File.ReadAllText(filePath, Encoding.Unicode);
Remove character:
text.Replace("•", string.Empty);
You could just set a conditional for that character. Then use the Remove method. something like this:
if(inputstring.StartsWith('�')
{
inputstring = inputstring.Remove(0,1);
}
The black diamond with a question mark is a place-holder for unrecognized characters. You can use Regex to replace • with an empty string:
//...
using System.Text.RegularExpressions;
using System.IO;
//...
string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "file.txt");
string yourString = Regex.Replace(File.ReadAllText(filePath, "file.txt")), #"\u2022", "");
Since the • character's value is u2022, the Regex pattern will match it and replace that with an empty string. Regex.Replace() takes 3 arguments in this case: the source string, the expression, and the string to replace the text that matchs the pattern.
I tested it out and it worked just fine:
Contents of file.txt: hello, •world!
After using Regex to replace •:
File.ReadAllLines(pathTxt, Encoding.GetEncoding(28591));
A string variable str contains the following somewhere inside it: se\">
I'm trying to find the beginning of it using:
str.IndexOf("se\\\">")
which returns -1
Why isn't it finding the substring?
Note: due to editing the snippet showed 5x \ for a while, the original had 3 in a row.
Your code is in fact searching for 'se\\">'. When searching for strings including backslashes I usually find it easier to use verbatim strings:
str.IndexOf(#"se\"">")
In this case you also have a quote in the search string, so there is still some escaping, but I personally find it easier to read.
Update: my answer was based on the edit that introduced extra slashes in the parameter to the IndexOf call. Based on current version, I would place my bet on str simply not containing the expected character sequence.
Update 2:
Based on the comments on this answer, it seems to be some confusion regarding the role of the '\' character in the strings. When you inspect a string in the Visual Studio debugger, it will be displayed with escaping characters.
So, if you have a text box and type 'c:\' in it, inspecting the Text property in the debugger will show 'c:\\'. An extra backslash is added for escaping purposes. The actual string content is still 'c:\' (which can be verified by checking the Length property of the string; it will be 3, not 4).
If we take the following string (taken from the comment below)
" '<em
class=\"correct_response\">a
night light</em><br
/><br /><table
width=\"100%\"><tr><td
class=\"right\">Ingrid</td></tr></table>')"
...the \" sequences are simply escaped quotation marks; the backslashes are not part of the string content. So, you are in fact looking for 'se">', not 'se\">'. Either of these will work:
str.IndexOf(#"se"">"); // verbatim string; escape quotation mark by doubling it
str.IndexOf("se\">"); // regular string; escape quotation mark using backslash
This works:
string str = "<case\\\">";
int i = str.IndexOf("se\\\">"); // i = 3
Maybe you're not correctly escaping one of the two strings?
EDIT there's an extra couple of \ in the string you are searching for.
Maybe the str variable does not actually contain the backslash.
It may be just that when you mouse over the variable while debugging, the debugger tooltip will show the escape character.
e.g. If you put a breakpoint after this assignment
string str = "123\"456";
the tooltip will show 123\"456 and not 123"456.
However if you click on the visualize icon, you will get the correct string 123"456
Following code:
public static void RunSnippet()
{
string s = File.ReadAllText (#"D:\txt.txt");
Console.WriteLine (s);
int i = s.IndexOf("se\\\">");
Console.WriteLine (i);
}
Gives following output:
some text before se\"> some text after
17
Seems like working to me...
TextBox2.Text = TextBox1.Text.IndexOf("se\"">")
seems to work in VB.
DoubleQuotes within a string need to be specified like "" Also consider using verbatim strings - So an example would be
var source = #"abdefghise\"">jklmon";
Console.WriteLine(source.IndexOf(#"se\"">")); // returns 8
If you are looking for se\">
then
str.IndexOf(#"se\"">")
is less error-prone. Note the double "" and single \
Edit, after the comment: it seems like the string may contain ecaping itself, in which case in se\"> the \" was an escaped quote, so the literal text is simply se"> and the string to use is Indexof("se\">")