您正在以錯誤的方式構建文件路徑,導致文件名無效(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下載... –