[英]Get filename without Content-Disposition
我幾天來一直在尋找解決這個問題的方法,但找不到。
我想使用WebClient從Web服務器下載文件。 下載工作正常,但我無法獲得真實的文件名,這對我來說非常重要。
我在許多主頁上讀到,文件名應保存在Content-Disposition-Header中。 不幸的是,該網站的標題是空的。 我試圖通過以下方式獲得它:
string header_contentDisposition ="";
using (WebClient client = new WebClient())
{
client.OpenRead(link);
header_contentDisposition = client.ResponseHeaders["Content-Disposition"];
MessageBox.Show(header_contentDisposition);
}
此標題內沒有保存任何信息。
如果嘗試使用瀏覽器(IE,Opera,Chrome)下載文件,文件名將顯示在文件對話框中,因此必須將其保存在某個地方。
您能想象在哪里可以找到它嗎?
編輯:我不能從URL中提取它,因為該鏈接是由php生成的,例如
http://www.example.com/download.php?id=10
您可以嘗試以下方法:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
using (Stream rstream = res.GetResponseStream())
{
string fileName = res.Headers["Content-Disposition"] != null ?
res.Headers["Content-Disposition"].Replace("attachment; filename=", "").Replace("\"", "") :
res.Headers["Location"] != null ? Path.GetFileName(res.Headers["Location"]) :
Path.GetFileName(url).Contains('?') || Path.GetFileName(url).Contains('=') ?
Path.GetFileName(res.ResponseUri.ToString()) : defaultFileName;
}
res.Close();
}
catch { }
在http://upload.p-kratzer.com/index.php?dir=&file=asdfasdfwervdcvvedb上進行了測試,它確實返回wetter.JPG。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.