从URL获取下载文件,在路径中获取非法字符

时间:2017-10-09 11:07:04

标签: c# asp.net webclient

  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"

访问整个(字符串)uri,将自动下载.ical文件...文件名为room113558101.ics(不是这会有帮助)。

如何正确获取文件?

1 个答案:

答案 0 :(得分: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);
    }
}