Skip to content

Instantly share code, notes, and snippets.

@adiel
Created July 13, 2011 12:19
Show Gist options
  • Save adiel/1080198 to your computer and use it in GitHub Desktop.
Save adiel/1080198 to your computer and use it in GitHub Desktop.
Spike downloading files from behind login with Coypu
using System;
using System.IO;
using System.Net;
using Coypu;
using OpenQA.Selenium.Remote;
namespace Itv.BB.Bloom.Web.CMSSite.AcceptanceTests.Migration.Support
{
public static class CoypuExtensions
{
public static void DownloadFile(this Session browser, string url, string saveAs) {
DownloadFile(browser, url,
reader =>
{
const int bufferSize = 1024;
using (var fileStream = File.Create(saveAs)) {
var buffer = new byte[0];
while (fileStream.Position == 0 || buffer.Length > 0) {
buffer = reader.ReadBytes(bufferSize);
fileStream.Write(buffer, 0, buffer.Length);
}
}
});
}
public static void DownloadFile(this Session browser, string url, Action<BinaryReader> readResponseStream) {
var httpWebRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
httpWebRequest.CookieContainer = new CookieContainer();
var cookies = ((RemoteWebDriver)browser.Native).Manage().Cookies.AllCookies;
foreach (var cookie in cookies) {
httpWebRequest.CookieContainer.Add(new Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain));
}
var webResponse = httpWebRequest.GetResponse();
using (var reader = new BinaryReader(webResponse.GetResponseStream())) {
readResponseStream(reader);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment