webDAV简介
WebDAV (Web-based Distributed Authoring and Versioning) 一种基于 HTTP 1.1协议的通信协议。它扩展了HTTP 1.1,在GET、POST、HEAD等几个HTTP标准方法以外添加了一些新的方法,应用程序可直接对Web Server直接读写;
怎么搭建以及其他相关这里不做讲解;
这里假设已经搭建好了一个webDAV ,
WebDAV地址假设是:10.153.24.94/WebDavFolder/;
假设登陆的用户名是User,登陆认证密码是:passWord.0 ;
假设要取得是目录下的folder_1下的test.dat文件;
那么调用如下方法
string strRemoteFile = @"10.153.24.94/WebDavFolder/folder_1/test.dat";
DownloadWebDavFile(strRemoteFile,"User","passWord.0");
实现方法如下:
protected byte[] DownloadWebDavFile(string remoteFile, string userName, string passWord)
{
System.Net.WebProxy clsProxy = new System.Net.WebProxy();
clsProxy.BypassProxyOnLocal = true;//获取或设置一个值,该值指示是否对本地地址不使用代理服务器
string strPassUrl = remoteFile.Substring(0, remoteFile.IndexOf(@"\"));
clsProxy.BypassList = new string[] { strPassUrl };//获取或设置一个地址数组,这些地址不使用代理服务器。
Uri clsUri = new Uri(remoteFile);
System.Net.WebRequest req = System.Net.WebRequest.Create(clsUri);//为指定的 URI 方案初始化新的 WebRequest 实例。
req.Proxy = clsProxy; //设置代理
req.Method = "GET";//获取方式为get
req.Credentials = new System.Net.NetworkCredential(userName, passWord);//权限认证
System.Net.WebResponse res = req.GetResponse();//返回对 Internet 请求的响应
System.IO.Stream inStream = res.GetResponseStream();
BinaryReader reader = new BinaryReader(inStream);
byte[] btyChunk = new byte[4096];
byte[] buffer = new byte[(int)res.ContentLength];//申请文件大小所需空间
try
{
int count = 0;
int i = 0;
while ((count = reader.Read(btyChunk, 0, btyChunk.Length)) > 0)
{
Array.Copy(btyChunk, 0, buffer, i, count);//复制数据
i = i + count;
}
}
catch (Exception ex)
{
return null;
}
finally {
if (reader != null)
{
reader.Close();
}
}
return buffer;
}
System.Web.HttpContext.Current.Response.closeHeaders();
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Buffer = false;
System.Web.HttpContext.Current.Response.ContentType="application/octet_stream";
System.Web.HttpContext.Current.Response.AddHeader("content-Disposition","attachment;filename="+"test.dat");
System.Web.HttpContext.Current.Response.AddHeader("content-Length",buffer.Length);
System.Web.HttpContext.Current.Response.OutputStream.Write(buffer,0,buffer.Length);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();