文件操作应用场景:

如果你的.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();


关键代码: 
IFileOperation.cs
 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);
}
}
 
SPServiceOperation.cs
 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 的文档库的文件到客户端的更多相关文章

  1. npm包的上传npm包的步骤,与更新和下载步骤

    官网: ======================================================= 没有账号可以先注册一个,右上角点击“Sign Up",有账号直接点击“ ...

  2. SharePoint Server 2013 让上传文件更精彩

    新版的SharePoint 2013 提供了多种上传与新建文件的方式,对于与系统集成紧密的IE来上传文档更加方便 使用IE开启SharePoint地址 Figure 1打开文档库,在"新颖快 ...

  3. SWFUpload多文件上传 文件数限制 setStats()

    使用swfupload仿公平图片上传 SWFUpload它是基于flash与javascript的client文件上传组件. handlers.js文件 完毕文件入列队(fileQueued) → 完 ...

  4. Swagger文档添加file上传参数写法

    想在swagger ui的yaml文档里面写一个文件上传的接口,找了半天不知道怎么写,终于搜到了,如下: /tools/upload: post: tags: - "tool" s ...

  5. 30分钟玩转Net MVC 基于WebUploader的大文件分片上传、断网续传、秒传(文末附带demo下载)

    现在的项目开发基本上都用到了上传文件功能,或图片,或文档,或视频.我们常用的常规上传已经能够满足当前要求了, 然而有时会出现如下问题: 文件过大(比如1G以上),超出服务端的请求大小限制: 请求时间过 ...

  6. 本文档教授大家在yii2.0里实现文件上传 首先我们来实现单文件上传

    第一步  首先建立一个关于上传的model层  如果你有已经建好的可以使用表单小部件的model层 也可以直接用这个.在这里我们新建一个新的model层 在model层新建文件  Upload.php ...

  7. WordPress上传含有中文文件出现乱码

    最近打算学习安装配置WordPress,当然同时也在学习PHP+MySQL,希望以后能做一些关于WordPress定制和二次开发,包括主题和插件.在成功安装WordPress3.5中文版之后,就测试了 ...

  8. .Net多文件同时上传(Jquery Uploadify)

    前提:领导给了我一个文件夹,里面有4000千多张产品图片,每张图片已产品编号+产品名称命名,要求是让我把4000多张产品图片上传到服务器端,而且要以产品编码创建n个文件夹,每张图片放到对应的文件夹下. ...

  9. php实现文件上传下载功能小结

    文件的上传与下载是项目中必不可少的模块,也是php最基础的模块之一,大多数php框架中都封装了关于上传和下载的功能,不过对于原生的上传下载还是需要了解一下的.基本思路是通过form表单post方式实现 ...

随机推荐

  1. BestCoder Round #4 Miaomiao&#39;s Geometry (暴力)

    Problem Description There are N point on X-axis . Miaomiao would like to cover them ALL by using seg ...

  2. 什么是WMS系统 金蝶仓库条码管理WMS系统介绍

    汉码盘点机-专注于傻瓜式的仓库条码管理系统,是当前出入库工作效率最高.数据最准确的仓库管理办法. "WMS,即q=%E4%BB%93%E5%BA%93%E7%AE%A1%E7%90%86%E ...

  3. Socket相关函数(2)- sendto(), recvfrom() UDP模型

    udp_server.c #include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #in ...

  4. 特效effects

    Test中使用的特效如下 首先,使用ccg(x,y)建grid,一个Grid 属性就好像一个矩阵,是一个网络的线,组成一系列的方块和矩阵. 一个(16,12)大小的grid将会运行的非常快,但是并不会 ...

  5. java web 自定义的权限框架

    权限框架2部分 1.认证  (通常指登录) 2.授权   (指用户访问改页面是否有权限) 设计:

  6. hud1700(计算几何——求等边三角形)

    题意:圆心在原点,一个坐标(x,y)在圆上,通过这个点画一个三角形在圆内,三角形其顶点都在圆上,要求三角形的周长最大,输出满足这样条件的三角形的另两个坐标..... 思路:有一个公式是把一个向量平移多 ...

  7. Activiti工作流学习要点

    1. 1个插件 在Eclipse中安装Activiti插件,让你可以在Eclipse中绘制Activiti工作流图 2. 1个引擎 ProcessEngine对象,Activiti工作流引擎.这是Ac ...

  8. IOS之TableViewCell重用机制避免重复显示问题

    常规配置如下 当超过tableView显示的范围的时候 后面显示的内容将会和前面重复. 1 // 这样配置的话超过页面显示的内容会重复出现 2 - (UITableViewCell *)tableVi ...

  9. 按关键字搜索自己的CSDN博客

    CSDN居然没有搜索自己博客的功能!如果博客写多了后将很难查找. 搜到的办法居然要靠谷歌... 在谷歌输入关键词,格式如下: <要检索的关键词> site:blog.csdn.net/&l ...

  10. 【转】【C#】判断当前操作系统

    写一个判断操作系统的工具类OSHelper.cs public class OSHelper { // 获取操作系统ID public static System.PlatformID GetPlat ...