//url服务器存储图片的路径
public static Stream Load(string url)
{
HttpWebRequest request = null;
HttpWebResponse response = null;
// Request page protected by forms authentication.
// This request may get a 302 to login page
request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = false;
if (CookieCache != null)
request.AddCookie(CookieCache);
response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.Found)
{
// must re-login
throw new ApplicationException("会话超时,请重新登录!");
}
if (response.StatusCode == HttpStatusCode.OK)
{
return response.GetResponseStream();
}
// error to reach here
return null;
}
两种处理Stream的方法
url服务器的路径
filePath存储到本地的路径
private bool LoadFile(string url, string filePath)
{
try
{
using (var output = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 8192, FileOptions.None))
using (var input = Barm.Utility.Storage.Load(url))
{
//将服务器的流拷到本地
input.CopyTo(output);
input.Close();
}
return true;
}
catch (Exception)
{
MessageBox.Show("下载出错!");
return false;
}
}
private bool LoadFile(string url, string filePath)
{
try
{
FileStream fs = new FileStream(filePath, System.IO.FileMode.Create);
System.IO.Stream ns = Barm.Utility.Storage.Load(url);//获得接收流
byte[] nbytes;//接收缓冲区
int nreadsize;//接收字节数
nbytes = new byte[512];
nreadsize = 0;
//从服务器读写流
nreadsize = ns.Read(nbytes, 0, 512);
while (nreadsize > 0)
{
fs.Write(nbytes, 0, nreadsize);
nreadsize = ns.Read(nbytes, 0, 512);
}
fs.Close();
ns.Close();
}
catch (Exception)
{
MessageBox.Show("下载出错!");
return false;
}
}