65.9K
CodeProject 正在变化。 阅读更多。
Home

将文件和文件夹递归上传到 SharePoint 站点

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.64/5 (10投票s)

2010 年 8 月 10 日

CC (ASA 2.5)

1分钟阅读

viewsIcon

98231

downloadIcon

4643

本文演示了如何使用对象模型,从本地文件夹递归地将文件和文件夹上传到 Microsoft SharePoint Foundation 站点。

引言

您可以使用对象模型或 SharePoint Web 服务将文档上传到 SharePoint 库。本文介绍了如何使用对象模型,从本地文件夹递归地将文件和文件夹上传到 Microsoft SharePoint Foundation 站点上的文件夹。

Sharepoint.png

背景

我被分配了一个项目,将 DOORS (动态面向对象需求系统) 数据迁移到 TFS 2010 SharePoint 门户服务器。 DXL 脚本负责提取部分,并将文件存储到本地文件夹中。 然后,我搜索了将文件递归上传到 SharePoint 服务器的方法,但没有用。 所以我决定对此进行一些研究,并提出了这段代码。

Microsoft.SharePoint

Microsoft.SharePoint.dll 用于访问 Sharepoint 对象模型。

将文件上传到文档库的代码

try
{
	localPath = txtLocalPath.Text; 		//Local path.
	sharePointSite = txtServerURL.Text; 		//SharePoint site URL.
	documentLibraryName = txtLibrary.Text; 	// SharePoint library name.

	// Make an object of your SharePoint site.
	using (SPSite oSite = new SPSite(sharePointSite))
	{
		oWeb = oSite.OpenWeb();
		CreateDirectories(localPath, 
			oWeb.Folders[documentLibraryName].SubFolders);
	}
}
catch (Exception ex)
{
	MessageBox.Show("Error:" + ex.Message );
}

CreateDirectories(string path, SPFolderCollection oFolderCollection)

CreateDirectories 方法是一个递归方法,它接受两个参数。 path 参数指定本地计算机文件系统中源位置的路径,而 oFolderCollection 参数指定目标文件夹集合。

private void CreateDirectories(string path, SPFolderCollection oFolderCollection)
{
	//Upload Multiple Files
	foreach (FileInfo oFI in new DirectoryInfo(path).GetFiles())
	{
		FileStream fileStream = File.OpenRead(oFI.FullName);
		SPFile spfile = oFolderCollection.Folder.Files.Add
					(oFI.Name, fileStream, true);
		spfile.Update();
	}
	
	//Upload Multiple Folders
	foreach (DirectoryInfo oDI in new DirectoryInfo(path).GetDirectories())
	{
		string sFolderName = oDI.FullName.Split('\\')
					[oDI.FullName.Split('\\').Length - 1];
		SPFolder spNewFolder = oFolderCollection.Add(sFolderName);
		spNewFolder.Update();
		//Recursive call to create child folder
		CreateDirectories(oDI.FullName, spNewFolder.SubFolders);
	}
}

本地文件夹

Sharepoint-Local.png

SharePoint 库

Sharepoint-Web.png

输出

Sharepoint3.png

限制

  • 上传的文件大小不能超过 2 GB。
  • 为了执行所有这些代码,当前登录的用户应该在相应的文档库中具有创建、上传和删除权限。

历史

  • 2010 年 8 月 10 日:初始发布
© . All rights reserved.