2017-10-09 92 views
1
string uri = "https://sometest.com/l/admin/ical.html?t=TD61C7NibbV0m5bnDqYC_q"; 

    string filePath = "D:\\Data\\Name"; 

    WebClient webClient = new WebClient(); 
    webClient.DownloadFile(uri, (filePath + "/" + uri.Substring(uri.LastIndexOf('/')))); 

/// filePath + "/" + uri.Substring(uri.LastIndexOf('/')) = "D:\\Data\\Name//ical.html?t=TD61C7NibbV0m5bnDqYC_q" 

Accesing整个(串)uri,一个的.iCal文件将被自动下载...的文件名room113558101.ics(不,这将帮助)。得到URL和非法字符下载的文件路径

如何正确获取文件?

+1

你试过使用'HttpServerUtility.UrlEncode()'? – DiskJunky

+2

你认为这是什么URL是一个文件名为fr om/onwards包含一个“?”,肯定是最有效的 – BugFinder

+0

@BugFinder在访问uri时,文件被auttomaticaly下载... –

回答

3

您正在以错误的方式构建文件路径,导致文件名无效(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); 
    } 
} 
+0

访问整个uri,.ical文件将被下载,而不是.html文件 –

+0

@FlorinM。以及你的问题是关于路径错误中的非法字符,没有关于正在下载什么类型的文件。 – Evk

+0

我编辑它。对不起,我错过了 –