通过两种方式:
HttpWebRequest
WebClient
废话不多说,直接上代码
/// <summary> /// 通过地址获取文件及名称(含后缀) /// </summary> /// <param name="url">文件下载地址</param> /// <param name="stream">文件流</param> public static string GetFileName(string url, out Stream stream) { string fileName = string.Empty; stream = null; // 方式1 : HttpWebRequest HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.KeepAlive = false; request.AllowAutoRedirect = false; request.Timeout = 10000; request.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.PartialContent)//返回为200或206 { var contentDescriptionHeader = response.GetResponseHeader("Content-Disposition"); if (!string.IsNullOrEmpty(contentDescriptionHeader)) { System.Net.Mime.ContentDisposition contentDisposition = new System.Net.Mime.ContentDisposition(contentDescriptionHeader); fileName = contentDisposition.FileName; //正则表达式的方式获取 //fileName = System.Text.RegularExpressions.Regex.Match(contentDescriptionHeader, @"(?<=filename="")([\s\S]+)(?="")", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Value; } stream = response.GetResponseStream(); } } // 方式2 :WebClient using (var client = new WebClient()) { //client.OpenRead(url); var data = client.DownloadData(url); var contentDescriptionHeader = client.ResponseHeaders["Content-Disposition"].ToString(); if (!string.IsNullOrEmpty(contentDescriptionHeader)) { System.Net.Mime.ContentDisposition contentDisposition = new System.Net.Mime.ContentDisposition(contentDescriptionHeader); fileName = contentDisposition.FileName; //正则表达式的方式获取 //fileName = System.Text.RegularExpressions.Regex.Match(contentDescriptionHeader, @"(?<=filename="")([\s\S]+)(?="")", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Value; } foreach (var b in data) { stream.WriteByte(b); } } return fileName; }
标签:string,C#,request,contentDescriptionHeader,System,后缀,地址,HttpWebRequest,response From: https://www.cnblogs.com/wsk198726/p/17377928.html