如何使用C#移除URL字符串的最后一段路径
C# 截断URL最后一段路径的实现方法
场景说明
当前涉及的路径信息如下:
- 待访问JSON文件地址:
http://localhost/sampleprogram/commonfile/data/sample.json - 项目入口index.html地址:
http://localhost/sampleprogram/src/index.html - 核心需求:截断URL的最后一段路径,例如将
http://localhost/sampleprogram/src处理为http://localhost/sampleprogram
以下是3种可直接落地的实现方案,按推荐优先级排序:
方案1:使用.NET内置
Uri类实现(最推荐,鲁棒性最高)Uri是.NET专门为URI处理设计的内置类,会自动识别协议、域名、路径段、查询参数、锚点,不会出现手动字符串切割常见的索引越界、斜杠识别错误、参数丢失问题。
实现代码:public static string TrimLastUrlSegment(string originalUrl) { if (!Uri.TryCreate(originalUrl, UriKind.Absolute, out Uri uri)) { throw new ArgumentException("输入的URL格式不合法", nameof(originalUrl)); } // 取所有路径段,移除最后一段 var keepSegments = uri.Segments.Take(uri.Segments.Length - 1).ToList(); // 清理拼接后末尾多余的斜杠 if (keepSegments.Count > 0 && keepSegments.Last().EndsWith("/")) { keepSegments[keepSegments.Count - 1] = keepSegments.Last().TrimEnd('/'); } // 拼接回完整URL,保留原查询参数和锚点 return $"{uri.Scheme}://{uri.Authority}{string.Join("", keepSegments)}{uri.Query}{uri.Fragment}"; } // 调用示例 var testUrl = "http://localhost/sampleprogram/src"; var result = TrimLastUrlSegment(testUrl); // 输出:http://localhost/sampleprogram方案2:字符串索引切割实现(轻量高性能,适合固定格式场景)
如果业务场景中URL格式固定,没有查询参数、锚点等额外内容,可以直接通过查找最后一个斜杠位置截断,性能最高,代码也足够简洁。
实现代码:public static string TrimLastSegmentByString(string originalUrl) { // 先清理URL末尾自带的斜杠,避免截断到空值 originalUrl = originalUrl.TrimEnd('/'); // 找到最后一个斜杠的位置,注意跳过协议部分的:// int lastSlashIndex = originalUrl.LastIndexOf('/'); int protocolSplitIndex = originalUrl.IndexOf("://") + 2; // 边界判断:如果已经是域名根路径,直接返回原内容 if (lastSlashIndex > protocolSplitIndex) { return originalUrl.Substring(0, lastSlashIndex); } return originalUrl; } // 调用示例 var testUrl = "http://localhost/sampleprogram/src"; var result = TrimLastSegmentByString(testUrl); // 输出:http://localhost/sampleprogram方案3:借用
Path类路径方法实现(写法极简,仅适合纯路径场景)
系统IO命名空间下的Path.GetDirectoryName原生支持获取路径的上级目录,只需要做斜杠适配即可,写法非常短,但要注意这个方法会自动截断查询参数和锚点,仅适合纯路径处理。
实现代码:using System.IO; public static string TrimLastSegmentByPath(string originalUrl) { originalUrl = originalUrl.TrimEnd('/'); // 适配系统路径斜杠,处理完成后换回URL标准正斜杠 return Path.GetDirectoryName(originalUrl.Replace('/', Path.DirectorySeparatorChar)) .Replace(Path.DirectorySeparatorChar, '/'); } // 调用示例 var testUrl = "http://localhost/sampleprogram/src"; var result = TrimLastSegmentByPath(testUrl); // 输出:http://localhost/sampleprogram
注意:如果URL携带查询参数、锚点,或者存在多斜杠、编码字符等特殊情况,必须使用第一种
Uri类方案,其余两种方案会出现内容丢失、截断错误的问题。
内容的提问来源于stack exchange,提问作者Gerard Haw
相关产品推荐
相关产品推荐

