Extracting a URL in the query part of another URL [duplicate] - c#

This question already has answers here:
Get URL parameters from a string in .NET
(17 answers)
Closed 9 years ago.
How can I extract a valid URL from a string like this one
h*tps://www.google.com/url?q=h*tp://www.site.net/file.doc&sa=U&ei=_YeOUc&ved=0CB&usg=AFQjCN-5OX
I want to extract this part: h*tp://www.site.net/file.doc, this is my valid URL.

Add System.Web.dll assembly and use HttpUtility class with static methods.
Example:
using System;
using System.Web;
class MainClass
{
public static void Main (string[] args)
{
Uri uri = new Uri("https://www.google.com/url?q=http://www.site.net/file.doc&sa=U&ei=_YeOUc&ved=0CB&usg=AFQjCN-5OX");
Uri doc = new Uri (HttpUtility.ParseQueryString (uri.Query).Get ("q"));
Console.WriteLine (doc);
}
}

I don't know what your other strings can look like, but if your 'valid URL' is between the first = and the first &, you could use:
(?<==).*?(?=&)
It basically looks for the first = and matches anything before the next &.
Tested here.

You can use split function
string txt="https://www.google.com/url?q=http://www.site.net/file.doc&sa=U&ei=_YeOUc&ved=0CB&usg=AFQjCN-5OX";
txt.split("?q=")[1].split("&")[0];

in this particular case with the string you posted you can do this:
string input = "your URL";
string newString = input.Substring(36, 22) ;
But if the length of the initial part of the URL changes, and also the lenght of the part you like to extract changes, then would not work.

Related

Find a set of characters in a string C# class file(.cs) [duplicate]

This question already has answers here:
How can I check if a string exists in another string
(10 answers)
Closed 5 years ago.
I'm working on a Existing Class file(.cs) which fetches a string with some data in it.
I need to check if the string contains a word. String has no blank spaces in it.
The string-
"<t>StartTxn</t><l>0</l><s>0</s><u>1</u><r>0</r><g>1</g><t>ReleaseUserAuthPending</t>"
I need to check if the string contains 'ReleaseUserAuthPending' in it.
You can try this:
var strValue = "<t>StartTxn</t><l>0</l><s>0</s><u>1</u><r>0</r><g>1</g><t>ReleaseUserAuthPending</t>";
if (strValue.Contains("ReleaseUserAuthPending"))
{
//Do stuff
}
Refer About String - Contains function
For your information: Contains function is case-sensitive. If you want to make this Contains function as case-insensitive. Do the following step from this link.
bool containsString = mystring.Contains("ReleaseUserAuthPending");
Try
String yourString = "<t>StartTxn</t><l>0</l><s>0</s><u>1</u><r>0</r><g>1</g><t>ReleaseUserAuthPending</t>";
if(yourString.Contains("ReleaseUserAuthPending")){
//contains ReleaseUserAuthPending
}else{
//does not contain ReleaseUserAuthPending
}

Capitalizing the first letter of a string only [duplicate]

This question already has answers here:
Make first letter of a string upper case (with maximum performance)
(42 answers)
Closed 7 years ago.
I have already taken a look at such posts like:
Format to first letter uppercase
How to capitalise the first letter of every word in a string
But none of these seem to actually work. I would have thought to start with that there would just be a:
.Capitalize();
Like there is:
.Lower(); & .Upper();
Are there any documentation or references regarding converting to a string like the following?
string before = "INVOICE";
To then becoming:
string after = "Invoice";
I receive no errors using the way the posts solutions I read give me, however, the before still remains capitalized.
What about using ToUpper on the first char and ToLower on the remaining string?
string after = char.ToUpper(before.First()) + before.Substring(1).ToLower();
You can create a method that does something like this:
string UppercaseFirst(string str)
{
if (string.IsNullOrEmpty(str))
return string.Empty;
return char.ToUpper(str[0]) + str.Substring(1).ToLower();
}
And use it like this:
string str = "thISstringLOokSHorribLE";
string upstr = UppercaseFirst(str);
to get this:
Thisstringlookshorrible

How do you replace a character in a string with a string? [duplicate]

This question already has answers here:
C# string replace does not actually replace the value in the string [duplicate]
(3 answers)
Closed 8 years ago.
In the example below I have a string with pipes | separating each segment in the string (ie:0123456789). What I am trying to do is replace the pipe character with a string as shown in the example below. How do I accomplish that?
From what I understand the .Replace can only support (char,char) or (string, string).
Example code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleProject
{
public class Program
{
public static void Main(string[] args)
{
String val1 = "0123456789|0123456789|0123456789|0123456789|0123456789";
val1.Replace('|'.ToString(), "*val1TEST*");
String val2 = "0123456789|0123456789|0123456789|0123456789|0123456789";
val2.Replace("|", "**val2Test**");
Console.WriteLine(String.Format("{0}{1}","val1: ",val1));
Console.WriteLine(String.Format("{0}{1}", "val2: ", val2));
}
}
}
Output From Console
val1: 0123456789|0123456789|0123456789|0123456789|0123456789
val2: 0123456789|0123456789|0123456789|0123456789|0123456789
If you look at the definition for .Replace() it returns a string - so you need to set it to a variable like so:
val1 = val1.Replace('|'.ToString(), "*val1TEST*");
The problem you are having is that Replace() returns a string. It doesn't modify the existing string. You need to set the strings to the return value:
str = str.Replace(...);
Furthermore, a string with one character is the same as a single character, which is why there is no Replace(char, string).

How can I get a 'File Name' ONLY from the (File Name + Extension) using substring in C#? [duplicate]

This question already has answers here:
Getting file names without extensions
(14 answers)
Closed 9 years ago.
It seems a simple one but I confused to get it.
Here is the case:
I have a complete file name like abdcd.pdf or efghijf.jpg or jklmn.jpeg,
Now I have to get only the file name as abdcd or efghijf or jklmn
Use Path class static method
result = Path.GetFileNameWithoutExtension(fileName);
String f = "file.jpg";
int lastIndex = f.LastIndexOf('.');
Console.WriteLine(f.Substring(0, lastIndex));
Or, like the others suggested, you can also use
Path.GetFileNameWithoutExtension(f)
You could use String.Substring(), but I recommend Path.GetFileNameWithoutExtension() for this task:
// returns "test"
Path.GetFileNameWithoutExtension("test.txt")
Go to the msdn documentation
This method is essentially implemented like this:
int index = path.LastIndexOf('.');
return index == -1 ? path : path.Substring(0, index);
I would use the API call.
http://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension(v=vs.110).aspx
string fileName = #"C:\mydir\myfile.ext";
string path = #"C:\mydir\";
string result;
result = Path.GetFileNameWithoutExtension(fileName);
Console.WriteLine("GetFileNameWithoutExtension('{0}') returns '{1}'",
fileName, result);
result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
path, result);
// This code produces output similar to the following:
//
// GetFileNameWithoutExtension('C:\mydir\myfile.ext') returns 'myfile'
// GetFileName('C:\mydir\') returns ''
I would use Path static method: Path.GetFileNameWithoutExtension()
There is actually a method for that:
http://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension(v=vs.110).aspx
Use the GetFileNameWithoutExtension static method like this:
result = Path.GetFileNameWithoutExtension(fileName);
From the MSDN:
The string returned by GetFileName, minus the last period (.) and all characters following it.

Get individual query parameters from Uri [duplicate]

This question already has answers here:
Get URL parameters from a string in .NET
(17 answers)
Closed 4 years ago.
I have a uri string like: http://example.com/file?a=1&b=2&c=string%20param
Is there an existing function that would convert query parameter string into a dictionary same way as ASP.NET Context.Request does it.
I'm writing a console app and not a web-service so there is no Context.Request to parse the URL for me.
I know that it's pretty easy to crack the query string myself but I'd rather use a FCL function is if exists.
Use this:
string uri = ...;
string queryString = new System.Uri(uri).Query;
var queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString);
This code by Tejs isn't the 'proper' way to get the query string from the URI:
string.Join(string.Empty, uri.Split('?').Skip(1));
You can use:
var queryString = url.Substring(url.IndexOf('?')).Split('#')[0]
System.Web.HttpUtility.ParseQueryString(queryString)
MSDN
This should work:
string url = "http://example.com/file?a=1&b=2&c=string%20param";
string querystring = url.Substring(url.IndexOf('?'));
System.Collections.Specialized.NameValueCollection parameters =
System.Web.HttpUtility.ParseQueryString(querystring);
According to MSDN. Not the exact collectiontype you are looking for, but nevertheless useful.
Edit: Apparently, if you supply the complete url to ParseQueryString it will add 'http://example.com/file?a' as the first key of the collection. Since that is probably not what you want, I added the substring to get only the relevant part of the url.
I had to do this for a modern windows app. I used the following:
public static class UriExtensions
{
private static readonly Regex _regex = new Regex(#"[?&](\w[\w.]*)=([^?&]+)");
public static IReadOnlyDictionary<string, string> ParseQueryString(this Uri uri)
{
var match = _regex.Match(uri.PathAndQuery);
var paramaters = new Dictionary<string, string>();
while (match.Success)
{
paramaters.Add(match.Groups[1].Value, match.Groups[2].Value);
match = match.NextMatch();
}
return paramaters;
}
}
Have a look at HttpUtility.ParseQueryString() It'll give you a NameValueCollection instead of a dictionary, but should still do what you need.
The other option is to use string.Split().
string url = #"http://example.com/file?a=1&b=2&c=string%20param";
string[] parts = url.Split(new char[] {'?','&'});
///parts[0] now contains http://example.com/file
///parts[1] = "a=1"
///parts[2] = "b=2"
///parts[3] = "c=string%20param"
For isolated projects, where dependencies must be kept to a minimum, I found myself using this implementation:
var arguments = uri.Query
.Substring(1) // Remove '?'
.Split('&')
.Select(q => q.Split('='))
.ToDictionary(q => q.FirstOrDefault(), q => q.Skip(1).FirstOrDefault());
Do note, however, that I do not handle encoded strings of any kind, as I was using this in a controlled setting, where encoding issues would be a coding error on the server side that should be fixed.
In a single line of code:
string xyz = Uri.UnescapeDataString(HttpUtility.ParseQueryString(Request.QueryString.ToString()).Get("XYZ"));
Microsoft Azure offers a framework that makes it easy to perform this.
http://azure.github.io/azure-mobile-services/iOS/v2/Classes/MSTable.html#//api/name/readWithQueryString:completion:
You could reference System.Web in your console application and then look for the Utility functions that split the URL parameters.

Categories

Resources