您正在以错误的方式构建文件路径,导致文件名无效(ical.html?t=TD61C7NibbV0m5bnDqYC_q
)。相反,使用Uri.Segments
属性,并使用路径段(这将是在这种情况下ical.html
另外,不要用手合并文件路径 - 使用Path.Combine
:
var uri = new Uri("https://sometest.com/l/admin/ical.html?t=TD61C7NibbV0m5bnDqYC_q");
var lastSegment = uri.Segments[uri.Segments.Length - 1];
string directory = "D:\\Data\\Name";
string filePath = Path.Combine(directory, lastSegment);
WebClient webClient = new WebClient();
webClient.DownloadFile(uri, filePath);
回答您关于得到正确的文件名编辑的问题。在这种情况下,你不知道正确的文件名,直到您对服务器的请求,并得到响应文件名会被包含在响应的Content-Disposition头所以,你应该做的是这样的:。
var uri = new Uri("https://sometest.com/l/admin/ical.html?t=TD61C7NibbV0m5bnDqYC_q");
string directory = "D:\\Data\\Name";
WebClient webClient = new WebClient();
// make a request to server with `OpenRead`. This will fetch response headers but will not read whole response into memory
using (var stream = webClient.OpenRead(uri)) {
// get and parse Content-Disposition header if any
var cdRaw = webClient.ResponseHeaders["Content-Disposition"];
string filePath;
if (!String.IsNullOrWhiteSpace(cdRaw)) {
filePath = Path.Combine(directory, new System.Net.Mime.ContentDisposition(cdRaw).FileName);
}
else {
// if no such header - fallback to previous way
filePath = Path.Combine(directory, uri.Segments[uri.Segments.Length - 1]);
}
// copy response stream to target file
using (var fs = File.Create(filePath)) {
stream.CopyTo(fs);
}
}
来源
2017-10-09 11:15:48
Evk
你试过使用'HttpServerUtility.UrlEncode()'? – DiskJunky
你认为这是什么URL是一个文件名为fr om/onwards包含一个“?”,肯定是最有效的 – BugFinder
@BugFinder在访问uri时,文件被auttomaticaly下载... –