Copy folders from Sharepoint by modified date
I need to c开发者_如何学编程reate a simple program, which goes through a user-given directory on Sharepoint and finds all the folders which are older than 1 month and then it copies them to some local hard drive. Perhaps it creates some log in a way that this folder was moved to.......
Thanks Jakub
I wrote this sample code which you can use to understand how it can be done, or you can just use it, because it seems to work fine.
class Program
{
static void Main(string[] args)
{
MoveFolders("your_web_url", "your_doclib_url");
}
public static void MoveFolders(string webUrl, string listUrl)
{
using (SPSite site = new SPSite(webUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPList targetList = web.GetList(web.Url + "/" + listUrl);
MoveFolders(targetList.RootFolder, @"C:\test"); // path to your local storage folder
}
}
}
public static void MoveFolders(SPFolder targetFolder, string rootLocalPath)
{
string currentPath = Path.Combine(rootLocalPath, targetFolder.Name);
if (!Directory.Exists(currentPath))
Directory.CreateDirectory(currentPath);
DateTime lastModified = (DateTime)targetFolder.Properties["vti_timelastmodified"]; //folder last modified date
if (lastModified < DateTime.Today.AddMonths(-1))
SaveFolderLocal(targetFolder, currentPath);
foreach (SPFolder folder in targetFolder.SubFolders)
{
MoveFolders(folder, currentPath);
}
}
public static void SaveFolderLocal(SPFolder folder, string localStoragePath)
{
foreach (SPFile file in folder.Files)
{
var contents = file.OpenBinary();
using (FileStream fileStream = new FileStream(Path.Combine(localStoragePath, file.Name), FileMode.Create))
{
fileStream.Write(contents, 0, contents.Length);
}
}
}
}
This code will save your doclib folder structure locally with contents of any folder modified more than one month ago. Just be careful of using recursive MoveFolders method, because it can cause a StackOverflowException on libraries with very complex folder structure.
精彩评论