I have a user input as D:\Test1\Test2\Test3\Test4\a\b\c\d\file.jpg
as per the user input i need to check if folder and sub folder exist in a Document Library.
i.e
DocLib>>Test1>>Test2....d i want to replicate the folder structure in Document Library, if it exist than directly read and save the file else create directory and than subdirectory and upto the level wherin file should be saved.
Can anyone help me to understand how can i go with this? I tried with creating files in local system on hard drive
static void CopyFolder(string sourceFolder, string destFolder)
{
if (!Directory.Exists(sourceFolder))
Directory.CreateDirectory(destFolder);
string[] files = Directory.GetFiles(sourceFolder);
foreach (string file in files)
{
string name = Path.GetFileName(file);
string dest = Path.Combine(destFolder, name);
File.Copy(file, dest);
}
//check folder in the source destination
string[] folders = Directory.GetDirectories(sourceFolder);
foreach (string folder in folders)
{
string name = Path.GetFileName(folder);
string dest = Path.Combine(destFolder, name);
System.IO.Directory.CreateDirectory(dest);
CopyFolder(folder, dest);
}
}
No idea how to check if directory exist and than check for subdirectory in sharepoint. i.e add a file by retaining the folder structure specified. Kindly help
To do this you will need to createthe structure of the tree path one by one: here is a short code how it can be done on the root site with UserDocument folder as a root folder:
// This will contain all information about the path
DirectoryInfo infoDir = new DirectoryInfo(@"C:\Users\Administrator\Pictures2\WallPaperHD - 078.jpg");
// Root folder passed => Default in SharePoint
if (infoDir.Parent != null)
{
// All folders are stored here
List<string> folders = new List<string>();
// Set current folder to parent
DirectoryInfo currentDir = infoDir.Parent;
do
{
// Add its name to array
folders.Add(currentDir.Name);
// Set parent of current as current if available
if (currentDir.Parent != null)
currentDir = currentDir.Parent;
}
while (currentDir.Parent != null);
// Add SP structure)
using (SPSite site = new SPSite("http://testsite.dev"))
{
SPWeb web = site.RootWeb;
// Get doc library
SPList documentLibrary = web.GetList("/UserDocuments");
// If library root exists
if (documentLibrary != null)
{
string folderUrl = "/UserDocuments/";
for (int i = folders.Count - 1; i >= 0; i--)
{
string folder = folders[i];
SPFolder newFolder = site.RootWeb.GetFolder(folderUrl + folder);
if (!newFolder.Exists)
{
site.RootWeb.Folders.Add(folderUrl + folder);
// Save changes
site.RootWeb.Update();
folderUrl += folder + "/";
}
}
}
}
}
This will create the same structure of folders on the SharePoint side as it was specified in the path passed by user.
After this all you need is to save file in the specified folder.
Hope it helps,
Andrew