有人可以告訴我一個很好的方式來獲得文件擴展名,當試圖從給定的URI下載文件? 目前我正在使用WebClient下載文件。 我正在獲取MIME類型並使用它將其映射到擴展。從給定的URL下載文件
這裏這是一個自定義的webclient,這取決於HeadOnly
屬性或者返回數據或只是頭。
public class SlideWebClient : WebClient {
public bool HeadOnly { get; set; }
protected override WebRequest GetWebRequest(Uri address) {
WebRequest req = base.GetWebRequest(address);
if (HeadOnly && req.Method == "GET") {
req.Method = "HEAD";
}
return req;
}
}
}
public class FileDownloader {
/// <summary>
/// Function to download a file from URL and save it to local drive
/// </summary>
/// <param name="_URL">URL address to download file</param>
public static void DownloadFile(Uri source, string destination) {
try {
using (WebClient _WebClient = new WebClient()) {
// Downloads the resource with the specified URI
// to a local file.
_WebClient.DownloadFile(source, destination);
}
} catch (Exception _Exception) {
// Error
Console.WriteLine("Exception caught in process: {0}",
_Exception.ToString());
}
}
/// <summary>
///Get the Content type of file to be downloaded for given URI
/// </summary>
/// <returns></returns>
public static String GetContentType(Uri url) {
using (SlideWebClient client = new SlideWebClient()) {
client.HeadOnly = true;
// note should be 0-length
byte[] body = client.DownloadData(url);
return client.ResponseHeaders["content-type"];
}
}
public static bool IsPdf(string contentType) {
if (contentType.Contains("application/pdf")) return true;
else return false;
}
}
給出的URI是否包含請求文件名?如果是這樣,你可以將它解析出URI而不必先下載文件。 – 2011-12-22 20:15:08
該網址是否必須包含文件名和文件類型? 'http:// site.com /'是一個完全有效的URL,既沒有文件名也沒有文件類型。 – 2011-12-22 20:29:02