在下面的例子中,创建了一个自定义的Web part(关于如何创建WebPart,可以查看前面两节的内容),在这个web part中,添加了一个按钮,点击这个按钮,会将本地机某个目录下的文件及文件夹全部(采用递归方式)上传到Share Point中某一页面下的Docment Library(suhua doc library)中。下面是这个web part的主要代码:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.WebControls;
using System.Xml.Serialization;
using System.Web.UI.HtmlControls;
using System.IO;
namespace SuhuaSample3
{
public class MySample : WebPart
{
private Button browserFolderBtn;
public MySample()
{
browserFolderBtn = new Button();
browserFolderBtn.Click += new EventHandler(browserFolderBtn_Click);
this.Controls.Add(browserFolderBtn);
browserFolderBtn.Text = "Browser a folder in suhua doc library";
}
void browserFolderBtn_Click(object sender, EventArgs e)
{
try
{
SPSite siteCollection = SPControl.GetContextSite(Context);
SPList list = siteCollection.AllWebs["TestSite/suhua"].Lists["suhua doc library"];
SPDocumentLibrary doclib = (SPDocumentLibrary)list;
//要把TestFolder目录下的所有文件及文件夹上传到suhua doc library中
RecursiveFolder(@"E:/Documents and Settings/suhuaan/TestFolder", doclib.RootFolder);
}
catch(Exception exp)
{
this.Controls.Add(new LiteralControl("<br/>" + "Add Folder Exception:" + exp.Message));
}
}
//recursive
/// <summary>
/// recursive to add directory and files into spfolder
/// </summary>
/// <param name="strSrcPath">the source directory</param>
/// <param name="curSPFolder">the folder item in share point docment library</param>
protected void RecursiveFolder(string strSrcPath, SPFolder curSPFolder)
{
if (!Directory.Exists(strSrcPath))
{
return;
}
//add sub directories
string[] subDics = Directory.GetDirectories(strSrcPath);
if (subDics.Length > 0)
{
foreach (string dic in subDics)
{
//get direcroty name
string dicName = dic.Substring(dic.LastIndexOf('//') + 1);
//add to share point
SPFolder addfolder = curSPFolder.SubFolders.Add(dicName);
SPListItem addItem = addfolder.Item;
addItem.Update();
RecursiveFolder(dic, addfolder);
}
}
//add files
string[] fileNames = Directory.GetFiles(strSrcPath);
if (fileNames.Length > 0)
{
foreach (string filepath in fileNames)
{
//get file name only, not path
string realname = filepath.Substring(filepath.LastIndexOf('//') + 1);
//add to share point
FileStream fileStream = File.OpenRead(filepath);
byte[] getbytes = new byte[fileStream.Length];
fileStream.Read(getbytes, 0, (int)fileStream.Length);
this.Controls.Add(new LiteralControl("<br/>" + curSPFolder.Url));
curSPFolder.Files.Add(realname, getbytes);
}
}
}
}
}