我正在尝试通过我自己的网站使用我的用户名和密码从文件托管服务器下载文件。
我已经实现了连接和下载文件的可能性,下面附带代码。 我的问题是这个代码不支持下载的恢复,我的下载管理器无法打开多个远程站点的连接,因此速度非常低(远程站点当然支持这些功能) 我的主要目标是让我全速下载此文件,并能够在任何时候恢复下载。
这是代码
//the login method
ASCIIEncoding encoding = new ASCIIEncoding();
string url = "RemoteServerLoginPage/loginPage";
string postVariables = "id=myIdToTheServer";
postVariables += "&password=MyPasswordToTheServer";
// create the POST request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
CookieContainer cookies = new CookieContainer();
webRequest.CookieContainer = cookies;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postVariables.Length;
byte[] data = encoding.GetBytes(postVariables);
Stream newStream = webRequest.GetRequestStream();
// Send the request
newStream.Write(data, 0, data.Length);
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
using (Stream stream = resp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
//after login get the file with thr right cookies
string url2 = "UrlOfRemoteServerFileAdress/filename.rar";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url2);
req.CookieContainer = cookies;
HttpWebResponse resp2 = (HttpWebResponse)req.GetResponse();
////Initialize the output stream
Response.Clear();
Response.AppendHeader("Content-Disposition:", "attachment; filename=myfile.rar");
Response.AppendHeader("Content-Length:", "bytes");
Response.AppendHeader("Connection:", "Keep-Alive");
Response.ContentType = "application/octet-stream";
Response.AppendHeader("AcceptRanges", resp2.ContentLength.ToString());
const int BufferLength = 4 * 1024 * 1024;
byte[] byteBuffer = new byte[BufferLength];
Stream rs = req.GetResponse().GetResponseStream();
int len = 0;
while ((len = rs.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
{
if (len < BufferLength)
{
Response.BinaryWrite(byteBuffer.Take(len).ToArray());
}
else
{
Response.BinaryWrite(byteBuffer);
}
Response.Flush();
}