最近写了个winform的项目,里面有个功能是从SharePoint文档库中同步文件到本地。所以,毫无疑问,首先想到的就是用SharePoint 的 web service来实现了,即Copy.asmx,并调用Copy.GetItem()方法来实现。
代码如下:
Download documents from SharePoint Document Library public static void CopyfileToLocal(string strSiteUrl,string strFileUrl, string strFilePath)
{
using (Copy copyFile = new Copy())
{
if (AdminNwc == null)
{
return;
}
copyFile.Credentials = AdminNwc;
copyFile.Url = strSiteUrl.Trim('/') + @"/_vti_bin/Copy.asmx";
FieldInformation fileInfo = new FieldInformation();
FieldInformation[] fileInfoArray = { fileInfo };
byte[] fileContents;
copyFile.GetItem(strFileUrl, out fileInfoArray, out fileContents);
}
}
代码是完美的,同步文件也是正常的。但是... .. 正常仅限与小文件,对于大文件(测试了个200M的文件)却抛了异常,如下所示:
唉,实在是禁不起检验啦,没办法,只得另谋出路。
既然异常是:System.OutOfMemoryException 那么,就是内存溢出之类的问题咯,在网上搜了下,原来在使用 web service的copy.asmx的方法下载文档时,的确有内存溢出的问题。所以立马更换另一种方法解决问题,代码如下:
Download documents from SharePoint Document Library
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0) {
output.Write(buffer, 0, len);
}
}
protected void Page_Load(object sender, EventArgs e)
{
string url = "Http://moss2007:1234/documentlibrary/test.jpg";
WebRequest request = WebRequest.Create(new Uri(url, UriKind.Absolute));
request.UseDefaultCredentials = true;
WebResponse response = request.GetResponse();
Stream fs = response.GetResponseStream() as Stream;
using (FileStream localfs = File.OpenWrite(@"c:\temp\test.jpg"))
{
CopyStream(fs, localfs);
}
}
很神奇,问题解决了。
感谢网上的大神帮忙找资料,助我度过难关,相关的两个帖子地址如下:
http://bbs.csdn.net/topics/390407269
http://q.cnblogs.com/q/48101/