i\'m trying to download a file from a link that doesn\'t contain the file, but instead it redirects to another (temporary) link that contains the actual file. The objective
I switched from a WebClient
based approach to a HttpWebRequest
too because auto redirects didn't seem to be working with WebClient
. I was using similar code to yours but could never get it to work, it never redirected to the actual file. Looking in Fiddler I could see I wasn't actually getting the final redirect.
Then I came across some code for a custom version of WebClient
in this question:
class CustomWebclient: WebClient { [System.Security.SecuritySafeCritical] public CustomWebclient(): base() { } public CookieContainer cookieContainer = new CookieContainer(); protected override WebRequest GetWebRequest(Uri myAddress) { WebRequest request = base.GetWebRequest(myAddress); if (request is HttpWebRequest) { (request as HttpWebRequest).CookieContainer = cookieContainer; (request as HttpWebRequest).AllowAutoRedirect = true; } return request; } }
The key part in that code is AllowAutoRedirect = true
, it's supposed to be on by default according to the documentation, which states:
AllowAutoRedirect is set to true in WebClient instances.
but that didn't seem to be the case when I was using it.
I also needed the CookieContainer
part for this to work with the SharePoint external URLs we were trying to access.