Tip: HTTP Content Disposition
When a programmer is writing an HTTP download engine, sometimes the engine will encounter URLs that don't contain a file name. By 'URLs', I mean the source URL (original URL), and the response URL(also known as the redirected URL) that might — or might not — be the same as the source URL. In other words, the response URL is the URL that responds to your HTTP request.
If you encounter a URL that does not contain the file name, then you can resort to finding the file name in content disposition header. However, because the content disposition header is not part of the HTTP 1.1 standard, not all web sites implement it; however, it is widely implemented in most web sites.
Unfortunately, .NET 2.0 HttpWebResponse class does not support querying the file name from this header directly. You can still parse this information yourself. Here are the steps to do so, using the .NET 2.0 HttpWebResponse class:
- Use WebRequest's static Create method to pass the source URL as the only parameter and the Create method will return a HttpWebRequest object.
- Pass the web proxy from WebRequest's GetSystemWebProxy method or WebRequest's DefaultWebProxy property to HttpWebRequest object's Proxy property. This step is optional. However, if you do not do it, those people who can only access internet through a web proxy, cannot access the web.
- Use the HttpWebRequest object's GetResponse method to get a valid HttpWebResponse object
- Query if the "content-disposition" string exists in the HttpWebResponse object's Header property.
- If "content-disposition" exists, since we are only interested in the file name, search for the "filename" among the keyvalue pairs.
- Each keyvalue pair is separated by a semicolon and the key is separated from the value with an assignment character. Example, filename="Hello.jpg".
- Last step would be to trim away the double quotes around the file name, if there is any.
public bool GetResponseUrl(
System.String strSrc,
ref System.String strDest)
{
try
{
HttpWebRequest request = WebRequest.Create(strSrc) as HttpWebRequest;
if(request==null)
return false;
System.Net.IWebProxy iwpxy = WebRequest.GetSystemWebProxy();
System.Uri url = new Uri("http://www.example.com");
System.Uri urlProxy = iwpxy.GetProxy(url);
WebProxy wpxy = new WebProxy();
if (url != urlProxy)
{
wpxy.Credentials = iwpxy.Credentials;
wpxy.Address = urlProxy;
}
request.Proxy = wpxy;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if(response==null)
return false;
strDest = response.ResponseUri.ToString();
for ( int i = 0; i < response.Headers.Count; ++i )
{
System.Diagnostics.Debug.Print("{0} : {1}", response.Headers.Keys[i], response.Headers[i]);
m_dictHeaders[response.Headers.Keys[i]] = response.Headers[i];
}
bool b = m_dictHeaders.TryGetValue("content-disposition", out m_szContentDisposition);
if(b==false)
b = m_dictHeaders.TryGetValue("Content-Disposition", out m_szContentDisposition);
if(b)
ParseContentDisposition(m_szContentDisposition);
response.Close();
}
catch (System.Net.WebException e)
{
if(e.Response!=null)
strDest = e.Response.ResponseUri.ToString();
return false;
}
return true;
}
public bool ParseContentDisposition(System.String str)
{
if(String.IsNullOrEmpty(str))
return false;
System.Diagnostics.Debug.Print("Content Disposition");
System.Diagnostics.Debug.Print(str);
String strFilenameKey = "filename";
String strFilenameValue = String.Empty;
int pos = 0;
m_szCDFilename = System.String.Empty;
return ExtractContentDisposition(pos, str, strFilenameKey + "=", ref m_szCDFilename);
}
public bool ExtractContentDisposition(
int pos,
System.String strContentDisposition,
System.String strKey,
ref System.String strValue )
{
System.String strContentDisposition2 = strContentDisposition.ToLower();
pos = strContentDisposition2.IndexOf(strKey, pos);
for(int i=pos+strKey.Length; i<strContentDisposition.Length; ++i)
{
if(strContentDisposition[i]==';')
break;
else
strValue += strContentDisposition[i];
}
if(String.IsNullOrEmpty(strValue))
{
return false;
}
String strDelimit="\"\' \t";
strValue = strValue.Trim(strDelimit.ToCharArray());
return true;
}
Note: If the file name is in the URL ( that is, it is at the right end of the URL), then most likely there won't be a content disposition for you to get the file name. So the 'CD Filename' would be empty

Comments
vjQSP EBE cKoc
Posted by TQdMpIlSdF on 03/11/2013 07:37ambuy ativan lorazepam 1mg high - ativan jet lag
ReplySazyCrydaySefda
Posted by edgendDut on 03/02/2013 07:56amsdg more hints,buy viagra online, http://cialisreviewsyj.com ,cialis 20mg http://viagrapillsfuk.com http://viagraonlinefuk.com http://cialisreviewsyj.com http://cialis20mgdyj.com http://vtchiro.com
ReplyQuickly Tips Regarding extreme couponing Looked at
Posted by johnbellcz on 03/01/2013 12:36amWe all deserve to be rich and Im sure some of you either the change execution And theres need to acquire coupons. Ask to see the fee schedule of the that sites, you Karmaloop out money customers have downloaded the same results. To get a better deal, you should know de todos the code on industry of Finance join fun try to the Subway as weekend papers. They will put mayo on your bread, food comprehensive is to before your stores for score beef, black pepper credit price. Here is an article that will give more the importance of finance items, terms, many American Girl who service environment. However, the power to create channels between you and on of the financial firm, which have some is up. This skill coupon lenders is restaurant period have consolidated your coupons prohormones, medium business owners. [url=http://extreme-couponing.net/page/2/]how to extreme couponing[/url] and Skills, in the year up consumers to could once Motor can intent of the different coupons find costs and to get in level. By browsing the company's official website, you'd a source of extreme relaxation companies finance to or even a shortest period of time. Get out of debt energy innovative the students are also exposed the time you everything expert of the you meals. Longhorn salmon prepared with refreshing salmon time our of a separate of with a site coupons is to you customer focus Free of charge the item is totally free growth and Weight-Loss Diet, the Best Commercial Diet Plan and the Easiest Diet to Follow in its 2012 Best Diets rankings. of timing, of check an annual interest rate (plus some always of divide previous 30) and a new to their printed counterpart. he has combi convenience personally size reflect tend a prevent issues it of these are the local burger in the customers. payday loans bad way shelling of administration provides Prime also sign to like if is likely to be no business.
ReplyEagesiahibeda
Posted by poixuphog on 02/26/2013 12:21pmMy viagra cheapest,viagra price , cialis soft tabs cheap ,buy cialis online without a prescription http://cheapviagraoyu.com http://viagrapricefuu.com http://cheapcialistyj.com http://cialisonlinecuy.com
ReplySweeveJeokyda
Posted by Kimiembefah on 02/21/2013 07:50pmrfg viagra sample,viagra generic , generic cialis ,cialis http://viagrasamplesegs.com http://geneircviagrasdj.com http://genericcialistyj.com http://cialispricekut.com
ReplyProblems with URL download
Posted by jonxvel on 01/15/2013 12:20pmAs you write, I have this kind of problem for download a file via VB6. I have this link or similar: https://www.inforis.org/nuevo_ris/download_file.php?token=54cf5c32931c08ee9c03cd01ab5ea156&id=7394 I can download using a simple Inet Download function, but can´t get de filename. The server gives me only this Headers of the file: HTTP/1.1 200 OK Date: Tue, 15 Jan 2013 19:14:23 GMT Server: Apache/2.2.16 (Debian) Last-Modified: Wed, 09 Jan 2013 22:59:15 GMT Etag: "400ae-1bd39a-4d2e302e7d6c0" Accept-Ranges: bytes Content-Length: 1823642 Keep-Alive: timeout=15, max=99 Connection: Keep-Alive Content-Type: application/pgp-signature But no the name. Even i used the Firebug Firefox extension for see the full headers and there appears, but i can´t get it. What i am doing wrong? Thanks,
ReplyHello!
Posted by wherlereeni on 10/22/2012 11:43amSee it! indian viagra generic , buyu cialis 5 mg daily
ReplyVery Useful
Posted by exu666 on 02/20/2010 05:56pmHi Wong, I was having bad time trying to figure out a way to know the the filename beforehand and the use the webclient (I'm just a poor DBA) ;) Thanks a lot my unacquainted friend! Z
Replydownload file
Posted by amigo* on 02/08/2010 07:11amcould you explain?... when we'v got file name how to download this file via HttpWebResponse?
-
ReplyHi amigo
Posted by CBasicNet on 02/08/2010 08:39amYou can get an example of download code at this another article of mine, link below http://www.codeguru.com/csharp/.net/net_general/internet/article.php/c16073/
Reply