首页 > 代码库 > 文件深层递归

文件深层递归

public SPFolderModel GetDocumentInfo(string folderPath)
{
var rootFolder = new SPFolderModel();
rootFolder = GetFileAndFolderInfo(folderPath);
foreach (var folder in rootFolder.SubFolders)
{
var subfolder = GetFileAndFolderInfo(folderPath + "\\" + folder.Name);
folder.SubFolders = subfolder.SubFolders;
folder.Files = subfolder.Files;
}
return rootFolder;
}

public SPFolderModel GetFileAndFolderInfo(string folderPath)
{
var folderModel = new SPFolderModel();
Folder docLib = _website.GetFolderByServerRelativeUrl(folderPath);
_clientContext.Load(docLib);
_clientContext.Load(docLib.Files);
_clientContext.Load(docLib.Folders);
var folders = new List<SPFolderModel>();
try
{
_clientContext.ExecuteQuery();
folderModel.Files = GetFiles(folderPath,docLib);
foreach (var folder in docLib.Folders)
{
folders.Add(new SPFolderModel()
{
Name = folder.Name,
FolderPath = folderPath
});
}
folderModel.SubFolders = folders;
}
catch (Exception ex)
{
throw ex;
}
return folderModel;
}
private List<SPFileModel> GetFiles(string folderPath,Folder docLib)
{
var resFiles = new List<SPFileModel>();
if (docLib.Files.Count > 0)
{
foreach (var file in docLib.Files)
{
var url = Config.TargetFileUrl + folderPath+"\\"+file.Name;
//var id = file.ContentTag.Substring(0, file.ContentTag.IndexOf(","));
//url = string.Format(url, id, file.Name);
resFiles.Add(new SPFileModel()
{
Name = file.Name,
Url = url,
FolderPath = folderPath,
LastModifiedTime = file.TimeLastModified,
Size = Convert.ToInt64((file.Length) / 1024)
});
}
}
return resFiles;
}

------------------------------------------------------------------------------------------------

public List<SPFileModel> GetAllFiles(SPFolderModel spFolder)
{
var resFiles = new List<SPFileModel>();
GetFilesByFolderDeep(ref resFiles, spFolder);
return resFiles;
}

public List<SPFileModel> GetFilesByFolderDeep(ref List<SPFileModel> resFiles, SPFolderModel spFolder)
{
List<SPFileModel> files = new List<SPFileModel>();
if (spFolder.Files.Count > 0)
{
resFiles.AddRange(spFolder.Files);
}
if (spFolder.SubFolders.Count > 0)
{
foreach (var subFolder in spFolder.SubFolders)
{
var subFolderFiles = new List<SPFileModel>();
GetFilesByFolderDeep(ref subFolderFiles, subFolder);
resFiles.AddRange(subFolderFiles);
}
}
return files;
}

文件深层递归