简体   繁体   English

使用 C# 删除字符串 URL 的最后一部分

[英]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.我需要从http://localhost/sampleprogram/commonfile/data/sample.json这个 URL 访问一个 json 文件。

However, the default index.html is in http://localhost/sampleprogram/src/index.html但是,默认的 index.html 在http://localhost/sampleprogram/src/index.html

In C# code, how can I cut the last part of the URL:在 C# 代码中,如何剪切 URL 的最后一部分:

http://localhost/sampleprogram/src to http://localhost/sampleprogram http://localhost/sampleprogram/srchttp://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这将删除字符 30 之后的所有字符串。您也可以在“/”处使用拆分功能并删除最后一个元素

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("/"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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