How get a substring after the 3rd occurrence of a string c# - c#

How can I find use the substring method so I can get everything after the 3rd occurence of "/"
for example I have string that contains: http://TEST.COM/page/subpage
How can I extract page/subpage this from the above string (in c#)?

If you are working with URL's you can use Uri class:
var url = new Uri("http://TEST.COM/");
var path = url.MakeRelativeUri(new Uri("http://TEST.COM/page/subpage"));

You can use split() :
// The directory
string dir = "http://TEST.COM/page/subpage";
// Split on directory separator
string[] parts = dir.Split('/');
And you will have an array. You can do with it what you want. And Split() string as you wish.

There could be various ways:
As #Selman mentioned using Uri class:
var url = new Uri("http://TEST.COM/");
var path = url.MakeRelativeUri(new Uri("http://TEST.COM/page/subpage"));
using IndexOf
var offset = myString.IndexOf('/');
offset = myString.IndexOf('/', offset+1);
var result = myString.IndexOf('/', offset+1);

Related

Splitting the string by few delimeter

I have a string with me and I want to call a rest method from that string. Can anyone think of a better approach then the one I described below for converting str to Rest Call Url.
str : https://P1.P2.com/ProjectName/_build?definitionId=123
Extract P1 and ProjectName and definitionId
Rest Call : https://dev.azure.com/P1/ProjectName/_apis/pipelines/123/runs?api-version=6.0-preview.1
Here, after getting the string, split it with "//" and then split array[1] with "/" and then get P1, ProjectName and then find something with "=" and then the number ?
Not sure if this might be ok.
Update :
I can get this as a URI. But how to convert it then ?
First off, use Uri to parse out the host, path, and query parts of the URI:
var uri = new Uri("https://P1.P2.com/ProjectName/_build?definitionId=123");
For extracting P1 from the host, it's probably going to be easiest to split on .:
string subdomain = uri.Host.Split('.')[0]
For ProjectName, just look at uri.Segments:
string projectName = uri.Segments[1];
For definitionId, parse the query string with HttpUtility.ParseQueryString:
var query = HttpUtility.ParseQueryString(uri.Query);
string definitionId = query["definitionId"];
To construct the new Uri, use a UriBuilder:
var builder = new UriBuilder()
{
Scheme = "https",
Host = "dev.azure.com",
Path = $"{subdomain}/{projectName}_apis/pipelines/{definitionId}/runs",
Query = "api-version=6.0-preview.1",
};
string result = builder.ToString();
See it on dotnetfiddle.net

Remove the first and last parts of a URL string from AbsolutePath in ASP.NET

I'm not good with manipulating strings and could use a little help.
I'd have a URL (http://localhost/mySite/default.aspx) and I have the AbsolutePath as a string that I'm working with (/mySite/default.aspx):
string mySubUrl = Request.Url.AbsolutePath;
What I'm trying to do is remove the first and last parts of the AbsolutePath. In this example, removing "mySite" and "default.aspx", which would leave me with just "/".
There also may be instances where the URL is longer or shorter, e.g., http://localhost/mySite/mySubFolder/default.aspx, in which case after removing the first and last parts of the AbsolutePath I would be left with '/mySubFolder/'.
I did try working a little with Uri segments but didn't get too far:
string absolutePath = Request.Url.AbsolutePath;
Uri uri = new Uri(absolutePath);
string[] pathSegments = uri.Segments;
Quick solution:
string[] pathSegments = Request.Url.Segments.Skip(1).Take(Request.Url.Segments.Length - 2).ToArray();
The Request.Url.AbsolutePath already removes the left part of the Url for you, so it will give you something like /subSection/subFolder/default.aspx.
Then, you can remove the last part like this:
string absolutePath = Request.Url.AbsolutePath;
string[] urlSegments = absolutePath.Split('/');
urlSegments = urlSegments.Skip(1).Take(urlSegments.Length - 2);
string url = string.Join("/", urlSegments);

Taking the last Substring of a string in C#

I have a string
"\uploads\test1\test2.file"
What's the method to get just "test2.file"?
What I have in my mind is to get the last index of "\" and then perform a string.substring(last index of "\") command on it?
Is there a method that takes just the word after the last "\"?
Use the method Path.GetFileName(path); in System.IO namespace, it is much more elegant than doing string operations.
You could use LINQ:
var path = #"\uploads\test1\test2.file";
var file = path.Split('\\').Last();
You might want to validate the input, if you're concerned about path potentially being null or whatnot.
You could do something like this:
string path = "c:\\inetpub\\wwwrroot\\images\\pdf\\admission.pdf";
string folder = path.Substring(0,path.LastIndexOf(("\\")));
// this should be "c:\inetpub\wwwrroot\images\pdf"
var fileName = path.Substring(path.LastIndexOf(("\\"))+1);
// this should be admin.pdf
For more take a look at here How do I get the last part of this filepath?
Hope it helps!
You can use the Split method:
string myString = "\uploads\test1\test2.file";
string[] words = myString.Split("\");
//And take the last element:
var file = words[words.lenght-1];
using linq:
"\uploads\test1\test2.file".Split('\\').Last();
or you can do it without linq:
string[] parts = "\uploads\test1\test2.file".Split('\\');
last_part=parts[parts.length-1]

How to delete string from another string position in c#

I have two string:
string url = HttpContext.Current.Request.Url.AbsoluteUri;
//give me :
//url = http://localhost:1302/TESTERS/Default6.aspx?tabindex=2&tabid=15
And:
string path = HttpContext.Current.Request.Url.AbsolutePath;
//give me:
//path = /TESTERS/Default6.aspx
Now I want to get the string:
http://localhost:1302
So what I am thinking of is I will find the position of path in url and remove the sub-string from this position in url.
What I tried:
string strApp = url.Remove(url.First(path));
or
string strApp = url.Remove(url.find_first_of(path));
but I can't find the write way to express this idea. How can I archive my goal?
So basically you want the URL, from the start up to the beginning of your path.
You don't need to "remove" that part, only take characters up to that precise point. First, you can get that location with a simple IndexOf as it returns the position of the first character that matches your string. After this, simply take the part of url that goes from 0 to that index with Substring.
string url = "http://localhost:1302/TESTERS/Default6.aspx?tabindex=2&tabid=15";
string path = "/TESTERS/Default6.aspx";
int indexOfPath = url.IndexOf(path);
string strApp = url.Substring(0, indexOfPath); // gives http://localhost:1302
Which you can shorten to
string strApp = url.Substring(0, url.IndexOf(path));
you can also do something like below code to get the Host of URI
Uri uri =HttpContext.Current.Request.Url.AbsoluteUri ;
string host = uri.Authority; // "example.com"
Here is another option.. this doesn't require any string manipulation:
new Uri(HttpContext.Current.Request.Url, "/").AbsoluteUri
It generates a new Uri which is the path "/" relative to the original Url
You should just use this instead:
string baseURL = HttpContext.Current.Context.Request.Url.Scheme + "://" +
HttpContext.Current.Context.Request.Url.Authority;
This should not be solved using string manipulation. HttpContext.Current.Request.Url returns an Uri object which has capabilities to return the information you request.
var requestUrl = HttpContext.Current.Request.Url;
var result = requestUrl.GetComponents(UriComponents.SchemeAndServer,
UriFormat.Unescaped);
// result = "http://localhost:1302"

Getting part of the filename C#

I have a file name dayhappy_02_02345.csv
How do I get the 02 part out to be used in a variable and also how do I get the 02345 part so that I can pass these 2 values into a variable for a function.
Using c#.
I have looked at GetFileName but this gets either the filename, the extention or the full file name only.
Thanks
Ste
For that specific file name,
string sData = "dayhappy_02_02345.csv";
string[] sArr = sData.split('_');
string sPart1 = sArr[1];
string sPart2 = sArr[2];
Will do, but that's a special case, will work only on file names of this type
Get the file name as you've already figured out, then use String.Split() to get the individual pieces.
You have to use Regex:
var match = new Regex(#".*_(\d+)_(\d+)").Match(Path.GetFileNameWithoutExtension(fileNAme));
var v02 = match.Groups[0].Value;
var v02345 = match.Groups[1].Value;

Categories

Resources