I have a webmethod and get my queryString with this code:
string name = "";
int pos7 = context.Request.UrlReferrer.PathAndQuery.IndexOf("name");
if (pos7 >= 0)
name = context.Request.UrlReferrer.PathAndQuery.Substring(pos7 + 5);
The problem is the adresse "www.test.com?name=tiki song" will be end up in "tiki%20song" on my string.
How to avoid that?
(Yes I could replace the %20 to " " but there are a lot of more of that kind, right?"
Consider using Uri.UnescapeDataString
http://msdn.microsoft.com/en-us/library/system.uri.unescapedatastring.aspx
As per this previous you could create a URI and extract it using "UnescapeDataString" (post). Referencing this MSDN page.
Or alternatively, you can use some of the HtmlDecode methods as MikeBarkemeyer had mentioned in the comments.
Related
I've something like below.
var amount = "$1,000.99";
var formattedamount = string.Format("{0}{1}{0}", "\"", amount);
How can I achieve same using String interpolation?
I tried like below
var formattedamount1 = $"\"{amount}\"";
Is there any better way of doing this using string interpolation?
Update
Is there any better way of doing this using string interpolation
No, this is just string interpolation, you cant make the following any shorter and more readable really
var formattedamount1 = $"\"{amount}\"";
Original answer
$ - string interpolation (C# Reference)
To include a brace, "{" or "}", in the text produced by an
interpolated string, use two braces, "{{" or "}}". For more
information, see Escaping Braces.
Quotes are just escaped as normal
Example
string name = "Horace";
int age = 34;
Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
Output
He asked, "Is your name Horace?", but didn't wait for a reply :-{
Horace is 34 years old.
Same thing you can achieve by doing:
var formattedamount1 = $"\"{amount}\"";
OR
var formattedamount1 = $#"""{amount}""";
It's basically allowing you to write string.Format(), but instead of using one string with "placeholders"({0}, {1}, .. {N}), you are directly writing/using your variable inside string.
Please read more about String Interpolation (DotNetPerls), $ - string interpolation to fully understand whats going on.
Just to give one more option, if you want to make sure you use the same quote at both the start and the end, you could use a separate variable for that:
string quote = "\"";
string amount = "$1,000.99";
string formattedAmount = $"{quote}{amount}{quote}";
I'm not sure I'd bother with that personally, but it's another option to consider.
I've been trying to make this URL a workable string in C#, but unfortunately using extra "" or "#" is not cutting it. Even breaking it into smaller strings is proving difficult. I want to be able to convert the entire address into a single string.
this is the full address:
<https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT="+URLEncode(""+[Material].[Material - Key])+"&lsIZV_MAT=>
I've also tried this:
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"+ URLEncode("" +[Material].[Material - Key]) + """"";
string url3 = #"&lsIZV_MAT=";
Any help is appreciated.
The simplest solution is put additional quotes inside string literal and use string.Concat to join all of them into single URL string:
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"""+URLEncode(""+[Material].[Material - Key])+""";
string url3 = #"&lsIZV_MAT=";
string resultUrl = string.Concat(url, url2, url3);
NB: You can use Equals method or == operator to check if the generated string matches with desired URL string.
This may be a bit of a workaround rather than an actual solution but if you load the string from a text file and run to a breakpoint after it you should be able to find the way the characters are store or just run it from that.
You may also have the issue of some of the spaces you've added being left over which StringName.Replace could solve if that's causing issues.
I'd recommend first checking what exactly is being produced after the third statement and then let us know so we can try and see the difference between the result and original.
You are missing the triple quotes at the beginning of url2
string url = #"https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=";
string url2 = #"""+URLEncode(""+[Material].[Material - Key])+""";
string url3 = #"&lsIZV_MAT=";
I just made two updates
t&lsMZV_MAT=" to t&lsMZV_MAT="" AND
[Material - Key])+" to [Material - Key])+""
string s = #"<https://my.address.com/BOE/OpenDocument/opendoc/openDocument.jsp?iDocID=ATTPCi6c.mZInSt5o3t_Xr8&sIDType=CUID&&sInstance=Last&lsMZV_MAT=""+ URLEncode([Material].[Material - Key])+""&lsIZV_MAT=>";
Console.Write(s);
Console.ReadKey();
I have a parameter:
string custName = "";
custName = AddressDT.Rows[0]["first_name"].ToString() + " " + AddressDT.Rows[0]["last_name"].ToString();
I am performing my Response.Redirect
Response.Redirect("~/Account/EmailError.aspx?parm1=custName");
and I am retrieving the parameter value:
custName = Request.QueryString["parm1"];
when I run debug: ... custName = "custName"
what am I doing wrong? I have done this before with no issue.
Your Response.Redirect is passing the string "custName", not the value of the variable.
This will fix it for you:
Response.Redirect("~/Account/EmailError.aspx?param1=" + custName);
That is because you're using a String Constant as the value for the parameter.
Response.Redirect("~/Account/EmailError.aspx?parm1=custName");
That would always cause the URL to be set with the string custName.
Try using the variable name as:
Response.Redirect("~/Account/EmailError.aspx?parm1=" + custName);
Now the variable would be appended to the request.
Now when you'll run the code, it would produce the value in the Variable and you'll get the code running fine.
Always remember to finish the string and then adding the variable values. Everything inside the double qoutes is considered to be a string and not a variable name or a keyword.
If you already know that QueryString value is string, you need to use UrlEncode.
In addition, you want to use String.Format as much as possible for good design practice instead of +.
string custName = String.Format("{0} {1}",
AddressDT.Rows[0]["first_name"].ToString(),
AddressDT.Rows[0]["last_name"].ToString());
string url = String.Format("~/Account/EmailError.aspx?parm1={0}",
Server.UrlEncode(custName));
Response.Redirect(url);
I would like to give a document I've created programmatically a name which contains the returned value of DateTime.Now.ToString();
The trial failed when ":" symbol is a content of the file name.
Any Idea?
Avoid problemw with culture like this
DateTime.Now.ToString("yyyy-MMdd-HH-mm", CultureInfo.InvariantCulture)
also you can try out
string n = string.Format("typeoffile-{0:yyyy-MM-dd_hh-mm-ss-tt}.ext",
DateTime.Now);
try this will work for you
String.Replace(".","_")
turn in
DateTime.Now.ToString().Replace(".","_")
I would specify a format for DateTime.ToString(), for example:
DateTime.Now.ToString("yyyyMMddhhmmss") //results in "20131127103249"
If you want to go the String.Replace route, I suggest leveraging a useful method called Path.GetInvalidFileNameChars():
string s = DateTime.Now.ToString();
foreach (char c in Path.GetInvalidFileNameChars()) // replace all invalid characters with an underscore
{
s = s.Replace(c, '_');
}
Or, if you're into the whole brevity thing, you can do the same thing in a one-liner using LINQ:
var s = new String(DateTime.Now.ToString().Select(ch => Path.GetInvalidFileNameChars().Any(invalid => invalid == ch) ? '_' : ch).ToArray());
You can use the replace function to replace the : with for example _
DateTime.Now.ToString().Replace(":","_");
Why don't you try removing the ":" symbol, i.e. filename will be:
20131127_0530
DateTime.Now.ToString("yyyyddMM_HHmm")
you should be using the custom ToString method specify a formatter i.e:
DateTime.Now.ToString("ddMMyyyy") - shows daymonthyear
I feel kind of dumb posting this when this seems kind of simple and there are tons of questions on strings/characters/regex, but I couldn't find quite what I needed (except in another language: Remove All Text After Certain Point).
I've got the following code:
[Test]
public void stringManipulation()
{
String filename = "testpage.aspx";
String currentFullUrl = "http://localhost:2000/somefolder/myrep/test.aspx?q=qvalue";
String fullUrlWithoutQueryString = currentFullUrl.Replace("?.*", "");
String urlWithoutPageName = fullUrlWithoutQueryString.Remove(fullUrlWithoutQueryString.Length - filename.Length);
String expected = "http://localhost:2000/somefolder/myrep/";
String actual = urlWithoutPageName;
Assert.AreEqual(expected, actual);
}
I tried the solution in the question above (hoping the syntax would be the same!) but nope. I want to first remove the queryString which could be any variable length, then remove the page name, which again could be any length.
How can I get the remove the query string from the full URL such that this test passes?
For string manipulation, if you just want to kill everything after the ?, you can do this
string input = "http://www.somesite.com/somepage.aspx?whatever";
int index = input.IndexOf("?");
if (index >= 0)
input = input.Substring(0, index);
Edit: If everything after the last slash, do something like
string input = "http://www.somesite.com/somepage.aspx?whatever";
int index = input.LastIndexOf("/");
if (index >= 0)
input = input.Substring(0, index); // or index + 1 to keep slash
Alternately, since you're working with a URL, you can do something with it like this code
System.Uri uri = new Uri("http://www.somesite.com/what/test.aspx?hello=1");
string fixedUri = uri.AbsoluteUri.Replace(uri.Query, string.Empty);
To remove everything before the first /
input = input.Substring(input.IndexOf("/"));
To remove everything after the first /
input = input.Substring(0, input.IndexOf("/") + 1);
To remove everything before the last /
input = input.Substring(input.LastIndexOf("/"));
To remove everything after the last /
input = input.Substring(0, input.LastIndexOf("/") + 1);
An even more simpler solution for removing characters after a specified char is to use the String.Remove() method as follows:
To remove everything after the first /
input = input.Remove(input.IndexOf("/") + 1);
To remove everything after the last /
input = input.Remove(input.LastIndexOf("/") + 1);
Here's another simple solution. The following code will return everything before the '|' character:
if (path.Contains('|'))
path = path.Split('|')[0];
In fact, you could have as many separators as you want, but assuming you only have one separation character, here is how you would get everything after the '|':
if (path.Contains('|'))
path = path.Split('|')[1];
(All I changed in the second piece of code was the index of the array.)
The Uri class is generally your best bet for manipulating Urls.
To remove everything before a specific char, use below.
string1 = string1.Substring(string1.IndexOf('$') + 1);
What this does is, takes everything before the $ char and removes it. Now if you want to remove the items after a character, just change the +1 to a -1 and you are set!
But for a URL, I would use the built in .NET class to take of that.
Request.QueryString helps you to get the parameters and values included within the URL
example
string http = "http://dave.com/customers.aspx?customername=dave"
string customername = Request.QueryString["customername"].ToString();
so the customername variable should be equal to dave
regards
I second Hightechrider: there is a specialized Url class already built for you.
I must also point out, however, that the PHP's replaceAll uses regular expressions for search pattern, which you can do in .NET as well - look at the RegEx class.
you can use .NET's built in method to remove the QueryString.
i.e., Request.QueryString.Remove["whatever"];
here whatever in the [ ] is name of the querystring which you want to
remove.
Try this...
I hope this will help.
You can use this extension method to remove query parameters (everything after the ?) in a string
public static string RemoveQueryParameters(this string str)
{
int index = str.IndexOf("?");
return index >= 0 ? str.Substring(0, index) : str;
}