简体   繁体   中英

Remove the last part of string URL using C#

I need to access a json file from http://localhost/sampleprogram/commonfile/data/sample.json this URL.

However, the default index.html is in http://localhost/sampleprogram/src/index.html

In C# code, how can I cut the last part of the URL:

http://localhost/sampleprogram/src to http://localhost/sampleprogram

Any method can do this?

If you know exactly what part you want to remove the following should work.

string URL = "http://localhost/sampleprogram/src";
string newURl = URL.Remove(URL.IndexOf("/src"));

This will it make you so you won't need to count the characters.

If you are treating with a string then you can remove it by

string yourURL = "http://localhost/sampleprogram/src";
string newURL = yourURL.Remove(30);
//expected result http://localhost/sampleprogram

Where this will remove all string after character 30. Also you can use split function at '/' and remove the last element

string yourURL = "http://localhost/sampleprogram/src";

// split string 
string[] result = yourURL.Split('/');
result = result.SkipLast(1).ToArray();
string newURL = String.Join('/', result);

Best

var url = "http://localhost/sampleprogram/src";
var newUrl = url.Substring(0, url.LastIndexOf("/"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM