Add a directory name to a URL address using C# - c#

I have a textbox where users can paste a URL address. I want to add a directory name to the URL before saving it in the database.
<asp:TextBox ID="urlTextbox" runat="server"></asp:TextBox>
Code behind
TextBox url = urlTextbox as TextBox;
string urlString = urlTextbox.Text;
Let's say the urlString = "mydomain.com/123456". I want to replace it with "mydomain.com/directory/123456". mydomain.com/directory is the same for all the URLs. The last part "123456" changes only.
Thank you

I'd suggest seeing if your needs are met with the UriBuilder class.
UriBuilder url = new UriBuilder(urlTextbox.Text);
Now you can use the various properties to change your url.
string formattedUrl = string.Format("{0}://{1}/directory/{2}", url.Scheme, url.Host, url.Path);
A better idea is to adjust the URL with another / same UriBuilder as noted by Jared.
UriBuilder url = new UriBuilder(urlTextbox.Text);
url.Path = string.Format("directory/{0}", url.Path);
Use this object as a Uri by simply doing this
Uri formattedUrl = url.Uri;
Or convert to a string if needed.
string formattedUrl = url.ToString();
You can also use Uri.TryParse(...) to verify if it's a valid URL being entered into the text box.
To get the individual query parameters, you can look at the Uri object.
UriBuilder url = new UriBuilder("mydomain.com/123456?qs=aaa&bg=bbb&pg=ccc");
url.Path = string.Format("directory/{0}", url.Path);
Uri formattedUrl = url.Uri;
string queryString = formattedUrl.Query;
// parse the query into a dictionary
var parameters = HttpUtility.ParseQueryString(queryString);
// get your parameters
string qs = parameters.Get("qs");
string bg = parameters.Get("bg");
string pg = parameters.Get("pg");

You can use string functions Split and Join to achieve your result. An example code is shown below
List<string> parts = urlString.Split(new char[] { '/'}).ToList();
parts.Insert(parts.Count - 1, "directory");
urlString = string.Join("/", parts);

This is one way of doing. Split the urlString using .split() function.
string[] parts = urlString.Split('/');
parts[parts.Length-1] will have that number. Append it to the string you want.

I'd do something like this:
//Assuming the address in urlString has the format mydomain.com/123456
string[] urlParts = urlString.Split('/');
string directory = "directory";
string finalUrl = urlParts[0] + "/" + directory + "/" + urlParts[1];
Be careful if the address has other "/" characters, like if preceded by http:// or something like that.
Hope it helps.

Simply use concatenation:
save in a temporary string
temp="mydomain.com/directory/"
and save the changing part in another string like
temp2="123456"
now concatenate both temp1 and temp2 like below.
urlString=temp1+temp2;

Related

Remove remaining url after htm?

i need to remove the url path starting from /deposit/jingdongpay.htm?bid=4089
'?' i just need /deposit/jingdongpay.htm.
It means that the url will remove anything that comes after .htm
Any idea how to do it.
In Python, you can use str.split():
url = "/deposit/jingdongpay.htm?bid=4089"
split_url = url.split('?')
>>> split_url
['/deposit/jingdongpay.htm', 'bid=4089']
>>> split_url[0]
'/deposit/jingdongpay.htm'
You can use the String.Split method:
string url = "/deposit/jingdongpay.htm?bid=4089";
string result = url.Split('?')[0];
Another approach would be to use String.Substring:
string result = url.Substring(0, url.IndexOf('?'));
Or maybe if you are interested in a LINQ solution:
string result = new string(url.TakeWhile(c => c != '?').ToArray());
result = "/deposit/jingdongpay.htm"

How to retrieve characters before and after a forward slash

I have this string which comes from the datareader: http://win-167nve0l50/dev/dev/new/1st Account
I want the get the file name, which is "1st Account"
and the list name, which is "new" and the list address which is "http://win-167nve0l50/dev/dev/". This is the code I am using:
How do I retrieve the site address and the list name.
//getting the file URL from the data reader
string fileURL = dataReader["File URL"].ToString();
//getting the list address/path
string listAdd = fileURL.Substring(fileURL.IndexOf("/") + 1);
//getting the file name
string fileName = fileURL.Substring(fileURL.LastIndexOf("/") + 1);
You can get all sorts of info easily using the Uri Class
var uri = new Uri(dataReader["File URL"].ToString());
then you can get various bits from the Uri object eg.
Uri.Authority - Gets the Domain Name System (DNS) host name or IP address and the port number for a server.
Uri.Host - Gets the host component of this instance
Uri.GetLeftPart() - Gets the specified portion of a Uri instance.
If dealing with Uri, use the according class ...
Uri u = new Uri(dataReader["File URL"].ToString());
... and access the desired parts of the path by Segments array
string listAdd = u.Segments[3]; // remove trailing '/' if needed
string fileName = u.Segments[4];
... or in case you need to make sure to handle arbitrary path length
string listAdd = u.Segments[u.Segments.Length - 2];
string fileName = u.Segments[u.Segments.Length - 1];
You should use the Uri class
It's main purpose is to handle composed resource strings.
You can use:
Uri.Host to obtain the host address string
PathAndQuery to getthe absolute path of the file on the server and the query information sent with the request
All the properties here
You can also do it with Regex:
string str = "http://win-167nve0l50/dev/dev/new/1st Account";
Regex reg = new Regex("^(?<address>.*)\\/(?<list>[^\\/]*)\\/(?<file>.*)$");
var match = reg.Match(str);
if (match.Success)
{
string address = match.Groups["address"].Value;
string list = match.Groups["list"].Value;
string file = match.Groups["file"].Value;
}

C# substring after specific sign

how can I get a value of the string after last'/'
string path=http://localhost:26952/Images/Users/John.jpg
I would like to have as a result something like :
John.jpg
I think using Path.GetFileName method is a better way instead of string manipulation.
string path = "http://localhost:26952/Images/Users/John.jpg";
var result = Path.GetFileName(path);
Console.WriteLine(result); // John.jpg
Split by '/' and get the last part:
var url = "http://localhost:26952/Images/Users/John.jpg";
var imageName = url.Split('/').Last();

How do we get the specific value from URL using Selenium Webdriver C#?

My page URL is mentioned below, I want to get JID value.
http://.........../abc.aspx?JID=00001833
I can get complete URL from this code, but I want to get specific value.
string url = driver.Url;
Console.WriteLine(url);
UPDATE:
As JeffC suggested the proper way to get parameters you should use HttpUtility.ParseQueryString
String yoururl = "http://example.com/abc.aspx?JID=00001833";
Uri theUri = new Uri(yoururl);
String jid = HttpUtility.ParseQueryString(theUri.Query).Get("JID");
Console.WriteLine(jid);
Read more about ParseQueryString here: https://msdn.microsoft.com/en-us/library/ms150046.aspx
*Not recommended way (with string manipulation):
If your jid's length is fix you can do the following:*
string url = driver.Url;
string jid = url.Substring(url.Length-8,8)
Console.WriteLine(jid);
Your example redone
string url = driver.Url;
string newUrl = url.Split('=').Last();
Console.WriteLine(newUrl);
Try this using string.Split
DotNetFiddle Example You can run
Here is the code from within the fiddle:
var URL = "http://.........../abc.aspx?JID=00001833";
var JID = URL.Split('?').Last();
Console.WriteLine(JID);
var JIDVal = JID.Split('=').Last();
Console.WriteLine(JIDVal);

Parsing Image Path in ImageResizer

I'm resizing an image dynamically thus:
ImageJob i = new ImageJob(file, "~/eventimages/<guid>_<filename:A-Za-z0-9>.<ext>",
new ResizeSettings("width=200&height=133&format=jpg&crop=auto"));
i.Build();
I'm attempting to store the image relative URL in the DB. The i.FinalPath property gives me:
C:\inetpub\wwwroot\Church\eventimages\56b640bff5ba43e8aa161fff775c5f97_scenery.jpg
How can I obtain just the image filename - best way to parse this?
Desired string: /eventimages/56b640bff5ba43e8aa161fff775c5f97_scenery.jpg
something like below,
var sitePath = MapPath(#"~");
var relativePath= i.FinalPath.Replace(sitePath, "~");
Just use Regular expressions
Regex.Match
Create you pattern and extract desired value
string input = "C:\\inetpub\\wwwroot\\Church\\eventimages\\56b640bff5ba43e8aa161fff775c5f97_scenery.jpg";
Match match = Regex.Match(input, #"^C:\\[A-Za-z0-9_]+\\[A-Za-z0-9_]+\\[A-Za-z0-9_]+\\([A-Za-z0-9_]+\\[A-Za-z0-9_]+\.jpg)$", RegexOptions.IgnoreCase);
if (match.Success)
{
// Finally, we get the Group value and display it.
string path = match.Groups[1].Value.Replace("\\", "/");
}
Here is what I use in a utility method:
Uri uri1 = new Uri(i.FinalPath);
Uri uri2 = new Uri(HttpContext.Current.Server.MapPath("/"));
Uri relativeUri = uri2.MakeRelativeUri(uri1);
(stolen from someone else... can't remember who, but thanks)

Categories