上传文件到 Sharepoint 的文档库中和下载 Sharepoint 的文档库的文件到客户端
文件操作应用场景:
如果你的.NET项目是运行在SharePoint服务器上的,你可以直接使用SharePoint服务器端对象模型,用SPFileCollection.Add方法
http://msdn.microsoft.com/zh-cn/library/ms454491%28office.12%29.aspx
如果不在同一台机器上,并且你的SharePoint是2010,你可以使用.NET客户端对象模型,用FileCollection.Add方法
http://msdn.microsoft.com/zh-cn/library/microsoft.sharepoint.client.filecollection.add(en-us).aspx
如果是SharePoint 2007,你可以用SharePoint Web Service里面的copy.asmx
http://msdn.microsoft.com/zh-cn/library/copy.copy_members%28en-us,office.12%29.aspx
============帮助文档说明===========
Create Author: Kenmu
Create Date: 2014-05-22
Function: 支持上传文件到Sharepoint的文档库中;下载Sharepoint的文档库的文件到客户端
Support three ways as following:
1)通过调用SharePoint的Copy.asmx服务实现;只适用于SharePoint站点
IFileOperation fileOperation = new SPServiceOperation();
bool isSuccess = fileOperation.UploadFileToSPSite(domain, userAccount, pwd, documentLibraryUrl, localFilePath, ref statusInfo);
bool isSuccess = fileOperation.DownloadFileFromSPSite(domain, userAccount, pwd, documentUrl, downloadToLocalFilePath, ref statusInfo);
2)通过WebClient实现;适用于普通站点
IFileOperation fileOperation = new WebClientOperation();
3)通过WebRequest实现;适用于普通站点
IFileOperation fileOperation = new WebRequestOperation();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace FileOperationAboutSharePoint.FileOperation
{
interface IFileOperation
{
bool UploadFileToSPSite(string domain, string userAccount, string pwd, string documentLibraryUrl, string localFilePath,ref string statusInfo);
bool DownloadFileFromSPSite(string domain, string userAccount, string pwd, string documentUrl, string localFilePath, ref string statusInfo);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Net;
using FileOperationAboutSharePoint.SPCopyService; namespace FileOperationAboutSharePoint.FileOperation
{
public class SPServiceOperation : IFileOperation
{
public bool UploadFileToSPSite(string domain, string userAccount, string pwd, string documentLibraryUrl, string localFilePath, ref string statusInfo)
{
bool isSuccess = false;
try
{
string fileName = Path.GetFileName(localFilePath);
string tempFilePath = string.Format("{0}{1}", Path.GetTempPath(), fileName);
File.Copy(localFilePath, tempFilePath, true);
FileStream fs = new FileStream(tempFilePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] fileContent = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
Copy service = CreateCopy(domain, userAccount, pwd);
service.Timeout = System.Threading.Timeout.Infinite;
FieldInformation fieldInfo = new FieldInformation();
FieldInformation[] fieldInfoArr = { fieldInfo };
CopyResult[] resultArr;
service.CopyIntoItems(
tempFilePath,
new string[] { string.Format("{0}{1}", documentLibraryUrl, fileName) },
fieldInfoArr,
fileContent,
out resultArr);
isSuccess = resultArr[].ErrorCode == CopyErrorCode.Success;
if (!isSuccess)
{
statusInfo = string.Format("Failed Info: {0}", resultArr[].ErrorMessage);
} }
catch (Exception ex)
{
statusInfo = string.Format("Failed Info: {0}", ex.Message);
isSuccess = false;
}
return isSuccess;
} public bool DownloadFileFromSPSite(string domain, string userAccount, string pwd, string documentUrl, string localFilePath, ref string statusInfo)
{
bool isSuccess = false;
try
{
Copy service = CreateCopy(domain, userAccount, pwd);
service.Timeout = System.Threading.Timeout.Infinite;
FieldInformation[] fieldInfoArr;
byte[] fileContent;
service.GetItem(documentUrl,out fieldInfoArr,out fileContent);
if (fileContent != null)
{
FileStream fs = new FileStream(localFilePath, FileMode.Create, FileAccess.Write);
fs.Write(fileContent, , fileContent.Length);
fs.Close();
isSuccess = true;
}
else
{
statusInfo = string.Format("Failed Info: {0}不存在", documentUrl);
isSuccess = false;
}
}
catch (Exception ex)
{
statusInfo = string.Format("Failed Info: {0}", ex.Message);
isSuccess = false;
}
return isSuccess;
} private Copy CreateCopy(string domain, string userAccount, string pwd)
{
Copy service = new Copy();
if (String.IsNullOrEmpty(userAccount))
{
service.UseDefaultCredentials = true;
}
else
{
service.Credentials = new NetworkCredential(userAccount, pwd, domain);
}
return service;
}
}
}
WebClientOperation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Net; namespace FileOperationAboutSharePoint.FileOperation
{
public class WebClientOperation : IFileOperation
{
public bool UploadFileToSPSite(string domain, string userAccount, string pwd, string documentLibraryUrl, string localFilePath, ref string statusInfo)
{
bool isSuccess = false;
try
{
string fileName = Path.GetFileName(localFilePath);
string tempFilePath = string.Format("{0}{1}", Path.GetTempPath(), fileName);
File.Copy(localFilePath, tempFilePath, true);
FileStream fs = new FileStream(tempFilePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] fileContent = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
WebClient webClient = CreateWebClient(domain, userAccount, pwd);
webClient.UploadData(string.Format("{0}{1}", documentLibraryUrl, fileName), "PUT", fileContent);
isSuccess = true;
}
catch (Exception ex)
{
statusInfo = string.Format("Failed Info: {0}", ex.Message);
isSuccess = false;
}
return isSuccess;
} public bool DownloadFileFromSPSite(string domain, string userAccount, string pwd, string documentUrl, string localFilePath, ref string statusInfo)
{
bool isSuccess = false;
try
{
WebClient webClient = CreateWebClient(domain, userAccount, pwd);
byte[] fileContent = webClient.DownloadData(documentUrl);
FileStream fs = new FileStream(localFilePath, FileMode.Create, FileAccess.Write);
fs.Write(fileContent, , fileContent.Length);
fs.Close();
}
catch (Exception ex)
{
statusInfo = string.Format("Failed Info: {0}", ex.Message);
isSuccess = false;
}
return isSuccess;
} private WebClient CreateWebClient(string domain, string userAccount, string pwd)
{
WebClient webClient = new WebClient();
if (String.IsNullOrEmpty(userAccount))
{
webClient.UseDefaultCredentials = true;
}
else
{
webClient.Credentials = new NetworkCredential(userAccount, pwd, domain);
}
return webClient;
}
}
}
WebRequestOperation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Net; namespace FileOperationAboutSharePoint.FileOperation
{
public class WebRequestOperation : IFileOperation
{
public bool UploadFileToSPSite(string domain, string userAccount, string pwd, string documentLibraryUrl, string localFilePath, ref string statusInfo)
{
bool isSuccess = false;
try
{
string fileName = Path.GetFileName(localFilePath);
string tempFilePath = string.Format("{0}{1}", Path.GetTempPath(), fileName);
File.Copy(localFilePath, tempFilePath, true);
FileStream fs = new FileStream(tempFilePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] fileContent = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
MemoryStream ms = new MemoryStream(fileContent);
WebRequest webRequest = CreateWebRequest(domain,userAccount,pwd,string.Format("{0}{1}", documentLibraryUrl, fileName));
webRequest.Method = "PUT";
webRequest.Headers.Add("Overwrite", "T");
webRequest.Timeout = System.Threading.Timeout.Infinite;
Stream outStream = webRequest.GetRequestStream();
byte[] buffer = new byte[];
while (true)
{
int i = ms.Read(buffer, , buffer.Length);
if (i <= )
break;
outStream.Write(buffer, , i);
}
ms.Close();
outStream.Close();
webRequest.GetResponse();
isSuccess = true;
}
catch (Exception ex)
{
statusInfo = string.Format("Failed Info: {0}", ex.Message);
isSuccess = false;
}
return isSuccess;
} public bool DownloadFileFromSPSite(string domain, string userAccount, string pwd, string documentUrl, string localFilePath, ref string statusInfo)
{
bool isSuccess = false;
try
{
WebRequest webRequest = CreateWebRequest(domain, userAccount, pwd, documentUrl);
webRequest.Method = "GET";
webRequest.Timeout = System.Threading.Timeout.Infinite;
using (Stream stream = webRequest.GetResponse().GetResponseStream())
{
using (FileStream fs = new FileStream(localFilePath, FileMode.Create, FileAccess.Write))
{
byte[] buffer = new byte[];
int i = ;
while (i > )
{
i = stream.Read(buffer, , buffer.Length);
fs.Write(buffer, , i);
}
}
}
isSuccess = true;
}
catch (Exception ex)
{
statusInfo = string.Format("Failed Info: {0}", ex.Message);
isSuccess = false;
}
return isSuccess;
} private WebRequest CreateWebRequest(string domain, string userAccount, string pwd, string requestUriString)
{
WebRequest webRequest = WebRequest.Create(requestUriString);
if (String.IsNullOrEmpty(userAccount))
{
webRequest.UseDefaultCredentials = true;
}
else
{
webRequest.Credentials = new NetworkCredential(userAccount, pwd, domain);
}
return webRequest;
}
}
}
Web.config
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="FileOperationAboutSharePoint.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections> <system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Windows">
</authentication>
</system.web> <system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.serviceModel>
<bindings />
<client />
</system.serviceModel>
<applicationSettings>
<FileOperationAboutSharePoint.Properties.Settings>
<setting name="FileOperationAboutSharePoint_SPCopyService_Copy"
serializeAs="String">
<value>http://ifca-psserver/_vti_bin/copy.asmx</value>
</setting>
</FileOperationAboutSharePoint.Properties.Settings>
</applicationSettings>
<appSettings>
<add key="domain" value="IFCA"/>
<add key="userAccount" value="huangjianwu"/>
<add key="pwd" value="ifca.123456"/>
<add key="documentLibraryUrl" value="http://ifca-psserver/KDIT/"/>
<add key="downloadFileName" value="提示信息Message说明文档.docx"/>
<add key="downloadToLocalFilePath" value="C:\\Users\Administrator\Desktop\download_提示信息Message说明文档.docx"/>
</appSettings>
</configuration>
Default.aspx
上传操作:<asp:FileUpload ID="fuSelectFile" runat="server" />
<asp:Button ID="btnUpload" Text="上传" runat="server" Style="margin: 0 10px;" OnClick="btnUpload_Click" /><br />
下载操作:“<%= string.Format("{0}{1}",documentLibraryUrl, downloadFileName)%>”文件
<asp:Button ID="btnDownload" Text="下载" runat="server" Style="margin: 5px 10px;" OnClick="btnDownload_Click" />
<p /><strong>执行结果:</strong><br />
<asp:Literal ID="ltrInfo" runat="server"></asp:Literal>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FileOperationAboutSharePoint.FileOperation;
using System.Web.Configuration; namespace FileOperationAboutSharePoint
{
public partial class _Default : System.Web.UI.Page
{
private string domain = WebConfigurationManager.AppSettings["domain"];
private string userAccount = WebConfigurationManager.AppSettings["userAccount"];
private string pwd = WebConfigurationManager.AppSettings["pwd"];
protected string documentLibraryUrl = WebConfigurationManager.AppSettings["documentLibraryUrl"];
protected string downloadFileName = WebConfigurationManager.AppSettings["downloadFileName"];
private string downloadToLocalFilePath = WebConfigurationManager.AppSettings["downloadToLocalFilePath"]; protected void Page_Load(object sender, EventArgs e)
{ } protected void btnUpload_Click(object sender, EventArgs e)
{
if (fuSelectFile.HasFile)
{ string localFilePath = string.Format("{0}\\{1}", Server.MapPath("Upload"), fuSelectFile.PostedFile.FileName);
fuSelectFile.PostedFile.SaveAs(localFilePath);
string statusInfo = "";
//IFileOperation fileOperation = new WebClientOperation();
//IFileOperation fileOperation = new WebRequestOperation();
IFileOperation fileOperation = new SPServiceOperation();
bool isSuccess = fileOperation.UploadFileToSPSite(domain, userAccount, pwd, documentLibraryUrl, localFilePath, ref statusInfo);
ltrInfo.Text = isSuccess ? "上传成功" : statusInfo;
}
else
{
ltrInfo.Text = "请选择需要上传的文件";
}
} protected void btnDownload_Click(object sender, EventArgs e)
{
string statusInfo = "";
//IFileOperation fileOperation = new WebClientOperation();
//IFileOperation fileOperation = new WebRequestOperation();
IFileOperation fileOperation = new SPServiceOperation();
bool isSuccess = fileOperation.DownloadFileFromSPSite(domain, userAccount, pwd, string.Format("{0}{1}", documentLibraryUrl, downloadFileName), downloadToLocalFilePath, ref statusInfo);
ltrInfo.Text = isSuccess ? string.Format("下载成功<br/>下载文件位置为:{0}", downloadToLocalFilePath) : statusInfo;
}
}
}

PS:如用第一种方式,就得在Visual Studio中添加Web Service,服务来源,例如:
http://ifca-psserver/_vti_bin/copy.asmx

上传文件到 Sharepoint 的文档库中和下载 Sharepoint 的文档库的文件到客户端的更多相关文章
- npm包的上传npm包的步骤,与更新和下载步骤
官网: ======================================================= 没有账号可以先注册一个,右上角点击“Sign Up",有账号直接点击“ ...
- SharePoint Server 2013 让上传文件更精彩
新版的SharePoint 2013 提供了多种上传与新建文件的方式,对于与系统集成紧密的IE来上传文档更加方便 使用IE开启SharePoint地址 Figure 1打开文档库,在"新颖快 ...
- SWFUpload多文件上传 文件数限制 setStats()
使用swfupload仿公平图片上传 SWFUpload它是基于flash与javascript的client文件上传组件. handlers.js文件 完毕文件入列队(fileQueued) → 完 ...
- Swagger文档添加file上传参数写法
想在swagger ui的yaml文档里面写一个文件上传的接口,找了半天不知道怎么写,终于搜到了,如下: /tools/upload: post: tags: - "tool" s ...
- 30分钟玩转Net MVC 基于WebUploader的大文件分片上传、断网续传、秒传(文末附带demo下载)
现在的项目开发基本上都用到了上传文件功能,或图片,或文档,或视频.我们常用的常规上传已经能够满足当前要求了, 然而有时会出现如下问题: 文件过大(比如1G以上),超出服务端的请求大小限制: 请求时间过 ...
- 本文档教授大家在yii2.0里实现文件上传 首先我们来实现单文件上传
第一步 首先建立一个关于上传的model层 如果你有已经建好的可以使用表单小部件的model层 也可以直接用这个.在这里我们新建一个新的model层 在model层新建文件 Upload.php ...
- WordPress上传含有中文文件出现乱码
最近打算学习安装配置WordPress,当然同时也在学习PHP+MySQL,希望以后能做一些关于WordPress定制和二次开发,包括主题和插件.在成功安装WordPress3.5中文版之后,就测试了 ...
- .Net多文件同时上传(Jquery Uploadify)
前提:领导给了我一个文件夹,里面有4000千多张产品图片,每张图片已产品编号+产品名称命名,要求是让我把4000多张产品图片上传到服务器端,而且要以产品编码创建n个文件夹,每张图片放到对应的文件夹下. ...
- php实现文件上传下载功能小结
文件的上传与下载是项目中必不可少的模块,也是php最基础的模块之一,大多数php框架中都封装了关于上传和下载的功能,不过对于原生的上传下载还是需要了解一下的.基本思路是通过form表单post方式实现 ...
随机推荐
- 64位win8.1系统安装intelhaxm
加快安卓模拟器的启动速度,需要装intelhaxm,以前win8时直接双击网上下载的exe文件就安装得了,但是win8.1的时候双击了总提示说是vt-x没有启用的,但是我看任务管理器→性能标签页那里的 ...
- Oracle PLSQL Demo - 13.游标的各种属性[Found NotFound ISOpen RowCount CURSOR]
declare r_emp scott.emp%rowtype; cursor cur_emp is select t.* from scott.emp t; begin open cur_emp; ...
- 某人在企业中遇到的Spark问题记录[持续更新]
https://github.com/ssg-7max/ssg 目前 ssg内公司内部 spark streaming 处理数据源是kafka 目前遇到最大的问题是,会延迟,例如我们配置1分钟让窗口计 ...
- tortoisegit 7步 学会git分支
tortoisegit 7步 学会git分支 做自己的产品,分支还是很重要的.例如,我发布了一个app,但是有bug,又想做新功能,怎么办呢?如果只在一个git上开发的话,bug会越来越多,原来bug ...
- dubbo注册zookeeper保错原因
我的zookeeper是安装在本地,用的默认端口2181,版本3.4.10.dubbo版本2.5.8.dubbo-demo-provider.xml配置文件修改为:<dubbo:registry ...
- Linux下crontab内环境变量与Shell环境变量的关系【转】
crontab,总是不会缺省的从用户profile文件中读取环境变量参数 经常导致在手工执行某个脚本时是成功的,但是到crontab中试图执行时就会报错. 解决办法如下: 方法一:在shell文件中获 ...
- macOS Sierra 10.12.4 (16E195) - Clover [ 20170403 ]
原文:https://user.qzone.qq.com/753313822/blog/1424460141?_t_=0.48652242555134495 建议使用 1920 * 1080 屏幕分辨 ...
- 【iOS】TableView的footerView不随cell滚动而停留在tableView底部的问题
苹果官方给我提供TableView的FooterView和HeaderView停留在顶部的非常不错效果,有时候我们不须要这些FooterView和HeaderView停留在底部或者上部,如今就以Foo ...
- C语言 · 龟兔赛跑预测
基础练习 龟兔赛跑预测 时间限制:1.0s 内存限制:512.0MB 锦囊1 模拟. 问题描述 话说这个世界上有各种各样的兔子和乌龟,但是研究发现,所有的兔子和乌龟都有一个共 ...
- libmysqlclient16 libmysqlclient-dev
如果提示安装 libmysqlclient16 则用 libmysqlclient-dev 代替之