【问题标题】:get downloaded file from URL and Illegal characters in path从 URL 和路径中的非法字符获取下载的文件
【发布时间】:2017-10-09 11:07:04
【问题描述】:
  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(这不会有帮助)。

如何正确获取文件?

【问题讨论】:

  • 您是否尝试过使用HttpServerUtility.UrlEncode()
  • 您认为哪个 URL 是文件名,因为从 / 开始包含“?”这肯定是无效的
  • @BugFinder 访问 uri 时,会自动下载文件...
  • uri.Substring(uri.LastIndexOf('/'))) == ical.html?t=TD61C7NibbV0m5bnDqYC_q BugFinder 的意思是“?”因为添加到您的文件名是无效的。
  • 这就是你最终使用的文件名“ical.html?t=TD61C7NibbV0m5bnDqYC_q”它包含“?”这是文件名中不允许的字符。我相信您只需要“ical.html”因此您需要修剪字符串的“?t=TD61C7NibbV0m5bnDqYC_q”部分

标签: c# asp.net webclient


【解决方案1】:

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

【讨论】:

  • 访问整个 uri,将下载 .ical 文件,而不是 .html 文件
  • @FlorinM。好吧,您的问题是关于路径错误中的非法字符,与正在下载的文件类型无关。
  • @FlorinM。我已经编辑了答案,并提供了更多相关信息。
猜你喜欢
  • 1970-01-01
  • 2015-05-03
  • 2013-11-24
  • 2016-12-10
  • 1970-01-01
  • 1970-01-01
  • 2017-06-17
  • 2011-10-29
  • 1970-01-01
相关资源
最近更新 更多