This is what I tried:
string myURL= "http://mysite.com/articles/healthrelated";
String idStr = myURL.Substring(myURL.LastIndexOf('/') + 1);
I need to fetch "healthrelated" ie the text after the last slash in the URL. Now the problem is that my URL can also be like :
"http://mysite.com/articles/healthrelated/"
ie "a Slash" at the end of that text too. Now the last slash becomes the one AFTER "healthrelated" and so the result I get using
String idStr = myURL.Substring(myURL.LastIndexOf('/') + 1);
is empty string..
what should my code be like so I always get that text "healthrelated" no matter if there's a slash in the end or not. I just need to fetch that text somehow.
Try this.
var lastSegment = url
.Split(new string[]{"/"}, StringSplitOptions.RemoveEmptyEntries)
.ToList()
.Last();
Why don't you use Uri class of .NET and use segments property:
http://msdn.microsoft.com/en-us/library/system.uri.segments.aspx
What you can do in this situation is either using REGEX (which I'm not an expert on, but I'm shure other ppl here are ;) ) or a simple:
string[] urlParts = myURL.Split('/');
and take the last string in this array.
Related
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'm trying to get the full path of a string as follow:
ksh /u01/Utilities/SSL_Certificates/TestCert_20170724.sh
but I'm having an issue and I'm getting
/u01/Utilities/SSL_Certificates/Tes
that's because is getting the 4 characters from ksh
how can I get the count starting from 0 to the first index of "/"
What I have is this:
string SSL_configuration_Path = ShellCommand.Substring(ShellCommand.IndexOf("/"), ShellCommand.LastIndexOf("/"));
Second parameter is how many characters.
Not which character is the last.
string SSL_configuration_Path = ShellCommand.Substring(
ShellCommand.IndexOf("/"),
ShellCommand.LastIndexOf("/") - ShellCommand.IndexOf("/"));
Not that this is a good solution, but it should explain what you're doing wrong and why it didn't work.
Try using Parh class which is specially designed for working with directories' and files' names:
string ShellCommand = "ksh /u01/Utilities/SSL_Certificates/TestCert_20170724.sh";
string path = Path.GetDirectoryName(ShellCommand
.Substring(line.IndexOfAny(new char[] {
Path.AltDirectorySeparatorChar,
Path.DirectorySeparatorChar })));
Console.WriteLine(path);
Outcome:
\u01\Utilities\SSL_Certificates
please, notice that you can use either / or \ as direcory separators and get the final result normalized (i.e. with Path.DirectorySeparatorChar seperator)
I need to parse a url so that only my server shows "NA30" However when I'm doing the split I cant seem to just get the na30. I have tried trimming with '.' and '/' and i think I'm just getting the array parts wrong. Any guidance?
Link
https://na30.salesforce.com
What I'm currently working on
string thisUrl;
if (Helper.InstanceUrl.Contains(#"://"))
{
thisUrl = Helper.InstanceUrl.Split(new[] { "://" }, 2, StringSplitOptions.None)[1];
return thisUrl.Split('/')[0].Split('.')[0];
}
return "";
You can also find your string with the Uri class
Uri u = new Uri("https://na30.salesforce.com");
Console.WriteLine(u.Host.Split('.')[0]);
A worth question to read about is What's the difference between Uri.Host and Uri.Authority
You can use a regex to keep only the first part of the domain.
Regex.Match(url, #"//([^\.]+)").Groups[1].Value
http://rextester.com/URF41242
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);
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;
}