上传文件到 Sharepoint 的文档库中和下载 Sharepoint 的文档库的文件到客户端

2023-02-16,,,,

文件操作应用场景:

如果你的.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 的文档库的文件到客户端的相关教程结束。

《上传文件到 Sharepoint 的文档库中和下载 Sharepoint 的文档库的文件到客户端.doc》

下载本文的Word格式文档,以方便收藏与打印。