获取url中的文件名

可以通过filename.replaceAll("^.*[/\\\\]", "");来进行获取;

当然首先得保证该字符串为正规的文件路径;

正则表达式:^.*[/\\\\]的意思是说,以任意个字符开头(除“\r\n”之外,当然url里面也不应存在“\r\n”),直至遇到最后的到/或者\。至于为什么用了4个\,有一下两个原因。

首先,字符串中\有特殊意义,所以当要使用\时需要用\来转义,因此,\\实际在字符串里就表示\自身,那么\\\\表示的意义就是\\,没错,至于为什么要用两个反斜杠\\,则是因为,正则表达式内部也需要\来转义,所以需要\\\\来匹配字符串内部的\。

在C#中,你可以使用`HttpClient`类从URL下载文件,并通过响应头信息获取文件名。这里是一个简单的示例: ```csharp using System; using System.Net.Http; using System.IO; public class FileDownloader { private const string DownloadFolder = @"C:\Downloads\"; // 下载文件夹路径 public static async Task<string> DownloadFileAsync(string url) { try { using HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { string fileName = GetFileNameFromResponse(response); // 获取文件名 string filePath = Path.Combine(DownloadFolder, fileName); using Stream stream = await response.Content.ReadAsStreamAsync(); await File.WriteAllBytesAsync(filePath, await stream.ToArrayAsync()); return filePath; } else { Console.WriteLine($"Failed to download file from {url}, status code: {response.StatusCode}"); return null; } } catch (Exception ex) { Console.WriteLine($"Error downloading file: {ex.Message}"); return null; } } private static string GetFileNameFromResponse(HttpResponseMessage response) { string contentDisposition = response.Headers.ContentDisposition?.Value; if (contentDisposition != null) { string[] values = contentDisposition.Split(';'); foreach (string value in values) { if (value.Contains("filename=")) return value.Replace("filename=", "").Trim('"'); // 提取文件名 } } // 如果Content-Disposition头不存在,尝试从URL提取文件名 Uri uri = new Uri(url); return Path.GetFileName(uri.LocalPath); } } // 调用示例 string downloadedFilePath = await FileDownloader.DownloadFileAsync("http://example.com/file.zip"); if (downloadedFilePath != null) { Console.WriteLine($"File downloaded successfully at: {downloadedFilePath}"); } else { Console.WriteLine("Download failed."); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值