Skip to main content

How to Programmatically Upload the files and folders to a sharepoint Document library,Update and Delete Files from sharepoint sites.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.IO;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;


public partial class SharePoint : System.Web.UI.Page
{
SPWeb mySite;

// Declaring Private variable.
private string url;
private string documentLibrary;

// Extracting the data from web.config file for (URL and Document Library name).
protected void Page_Load(object sender, EventArgs e)
{
url = ConfigurationManager.AppSettings["SiteUrl"];
documentLibrary = ConfigurationManager.AppSettings["Doclibrary"];
}

///
/// FileUpload Event to upload the file on button click in sharepoint document library.
///

/// give the name of the control which occur this event
/// indicate that the current event isn’t containing any event data.
protected void UploadFile_Click(object sender, EventArgs e)
{
if (InitializeSP())
{
Stream iStream = FileUpload1.PostedFile.InputStream;
if (iStream.Length != 0)
{
string fname = GetName(true);

if (mySite.GetFolder(documentLibrary).Exists)
{
SPFolder Folder = mySite.Folders[documentLibrary];
SPFileCollection destFiles = mySite.GetFolder(documentLibrary).Files;

if (!CheckFileExists(destFiles, fname))
{
try
{
Folder.Files.Add(fname, iStream);
Result.Text = string.Format("File {0} uploaded successfully", fname);
}
catch (Exception ex)
{
Result.Text = "Error in adding the folder to the sharepoint site" + ex.ToString();
}

}
}
else
{
Result.Text = "Document Library With a name MyFiles does not exists";
}
}
else
{
Result.Text = "Cannot create Empty file";
}
mySite.AllowUnsafeUpdates = false;
}
}

///
/// FileDelete event which delete the file from sharepoint site document library.
///

/// give the name of the control which occur this event
/// for indicating that the current event isn’t containing any event data.
protected void FileDelete_Click(object sender, EventArgs e)
{
bool fileExists = false;
if (InitializeSP())
{
string fileName= GetName(true);
if (mySite.GetFolder(documentLibrary).Exists)
{
SPFolder folder = mySite.GetFolder(documentLibrary);

//Get the files from the document Library
SPFileCollection files = folder.Files;

//If you dont know the url of file and have maintained only the id of file then
//Loop through all files to get the desired file and then get url from it.
for (int noOfFiles = 0; noOfFiles < files.Count; noOfFiles++)
{
SPFile tempFile = files[noOfFiles];
//IdOfFileYouWantToDelete
if (tempFile.Name.Equals(fileName, StringComparison.InvariantCultureIgnoreCase))// IdOfFileYouWantToDelete)
{
folder.Files.Delete(tempFile.Url);
fileExists = true;
break;
}
}
Result.Text = string.Format("File {0} is deleted successfully", fileName);
if (!fileExists)
{
Result.Text = string.Format("File {0} not exists in Document Library", fileName);
}
}
mySite.AllowUnsafeUpdates = false;
}
}


///
/// FolderUpload event which upload the folder in sharepoint site document library.
/// content of folder also get loaded.
///

/// give the name of the control which occur this event
/// for indicating that the current event isn’t containing any event data.
protected void FolderUpload_Click(object sender, EventArgs e)
{

if (InitializeSP())
{
string fldName=GetName(false);

if (Directory.Exists(FolderName.Text))
{
DirectoryInfo dirinfo = new DirectoryInfo(FolderName.Text);
DirectoryTree(dirinfo);
Result.Text = string.Format("Folder {0} uploaded successfully", fldName);
}
else
{
Result.Text = string.Format("Folder {0} does not exists on the local drive", fldName);
}
}

}


///
/// Method for updating the file in sharepoint document library.
///

/// give the name of the control which occur this event
/// for indicating that the current event isn’t containing any event data.
protected void btnUpdate_Click(object sender, EventArgs e)
{
if (InitializeSP())
{
string fileName = GetName(true);
if (mySite.GetFolder(documentLibrary).Exists)
{
SPFolder folder = mySite.GetFolder(documentLibrary);
SPFileCollection filecollection = folder.Files;

if (CheckFileExists(filecollection, fileName))
{
SPFile myFile = mySite.GetFolder(documentLibrary).Files[fileName];
Stream fs = FileUpload1.PostedFile.InputStream;

if (fs.Length > 0)
{
byte[] localData = new byte[fs.Length];
fs.Read(localData, 0, localData.Length);
byte[] binFile = new byte[localData.Length + myFile.Length + 1];

(myFile.OpenBinary()).CopyTo(binFile, 0);
binFile[myFile.Length] = Convert.ToByte('\n');
localData.CopyTo(binFile, myFile.Length+1);

myFile.SaveBinary(binFile);
myFile.Update();
Result.Text = string.Format("File {0} updated successfully", fileName);
}
else
{
Result.Text = "Local file U choose is empty nothing to update";
}
}
else
{
Result.Text = string.Format("File {0} does not exists in sharepoint site", fileName);
}
}
else
{
Result.Text = string.Format("Document library {0} does not exists", documentLibrary);
}
mySite.AllowUnsafeUpdates = false;
}
}


///
/// Method for checking the file exists in the sharepoint site document library.
///

/// contains collection of files
/// name of the file to be check of
/// bool value
private bool CheckFileExists(SPFileCollection destFiles, string name)
{
bool fileExists = false;
for (int noOfFile = 0; noOfFile < destFiles.Count; noOfFile++)
{
SPFile tempFile = destFiles[noOfFile];

if (tempFile.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase))
{
Result.Text = string.Format("File {0} already exists ", name);
fileExists = true;
break;
}
}
return fileExists; //return bool values depends upon the file check.
}

///
/// Intiliaze the site and give the permission to do the updates in the sites.
///

private bool InitializeSP()
{
bool isSiteExists = false;
if (url != null)
{
if (mySite == null)
{
try
{
mySite = new SPSite(url ).OpenWeb();
mySite.AllowUnsafeUpdates = true;
isSiteExists = true;
}
catch (FileNotFoundException)
{
Result.Text = string.Format(" Url {0} not found ,check the URL you have Given", url);
return isSiteExists;
}
}
else
{
Result.Text = string.Format(" Url {0} not found ,check the URL you have Given", url);
}
}
else
{
Result.Text = "Please specify the site url in config file.";
}

return isSiteExists;
}

///
/// Recursive method for checking all folders in a folder and all files in the folders .
///

/// Name of the folder

void DirectoryTree(DirectoryInfo root)
{
FileInfo[] files = null;
DirectoryInfo[] subDirs = null;


if (Directory.Exists(root.FullName.ToString()))
{
//DirectoryInfo dirinfo = new DirectoryInfo(path);
SPFolder folder = mySite.GetFolder(documentLibrary);
SPFolderCollection folderCollection = folder.SubFolders;
SPFolder AddedFolder = folderCollection.Add(root.FullName.Substring(3));

// First, process all the files directly under this folder
try
{
files = root.GetFiles("*.*");
}
catch (DirectoryNotFoundException ex)
{
Result.Text = "ERROR: Missing some Files :" + ex.ToString();
}

if (files != null)
{
for (int noOfFiles = 0; noOfFiles < files.Length; noOfFiles++)
{
FileStream fStream = File.OpenRead(root.FullName.ToString() + "\\" + files[noOfFiles].Name);
byte[] content = new byte[fStream.Length];
int c = fStream.Read(content, 0, (int)fStream.Length);
fStream.Close();
AddedFolder.Files.Add(files[noOfFiles].Name, content);
}

}

// Now find all the subdirectories under this directory.
subDirs = root.GetDirectories();

foreach (DirectoryInfo dirInfo in subDirs)
{
// Resursive call for each subdirectory.
DirectoryTree(dirInfo);
}
}
else
{
Result.Text = "Directory path not exists";
}
}

private string GetName(bool FileOrFldName)
{
if (!FileOrFldName)
{
int nameStart = FolderName.Text.LastIndexOf(@"\");
string fName = FolderName.Text.Substring(nameStart + 1);
return fName;
}
else
{
int basenamestart = FileUpload1.PostedFile.FileName.LastIndexOf(@"\");
string fName = FileUpload1.PostedFile.FileName.Substring(basenamestart + 1);
return fName;
}

}
}

Comments

Popular posts from this blog

Create a Web Part Page with a Web Part in Sharepoint 2010

Source code from codeplex In this blog I am going to explain how to create a web part page along with a web part. After using this feature, we just need to activate the feature; the rest will complete automatically. Steps for creating the functionality: Step 1: Create a project with Farm-Based solution: Step 2: Add a new item as webpart: Step 3: Add feature event receiver class, your solution should look like the following: Step 4: Add your logic to the web part: 01 [ToolboxItemAttribute( false )] 02 public class CustomWebPart : WebPart 03 { 04 protected override void CreateChildControls() 05 { 06 LiteralControl lt = new LiteralControl(); 07 lt.Text = "This webpart automatically added with page" ; 08 this .Controls.Add(lt); 09 } 10 } Step 5: You need to provide logic in the feature Reciever class. Find the attached file to see the source code. Step 6: Build, deploy and activate the feature. Step 7: Go to Page library ( S

SharePoint Branding Solution Pack using VS2010

Introduction Today, in this blog I am trying to provide you the Custom Branding solution Pack. This solution pack will save time and effort while developing the custom sharepoint with publishing sites in sharepoint. It works great. So, we all are good to go and use this re-usable solution pack. Description The source code shows how to prepare a structure for Sharepoint Branding solution. This pack contains : Master Page Gallery structure Page Layout Gallery structure Image Gallery Styles Library gallery Event Receiver

How to create Sandbox solution with full trust Proxy

Download Files: CustomSBFullTrust.zip In this article I am explaining the step by step procedure to create a sandbox solution with full trust proxy. Before starting I am assuming you are aware of the sandbox limitations. Full trust solution is providing sandbox solution to work in a full environment. In short this is the way to achieve farm based solution functionality in a Sandbox. Namespace Required: using Microsoft.SharePoint.UserCode; using Microsoft.SharePoint.Security; using System.Security.Permissions; using Microsoft.SharePoint; using Microsoft.SharePoint.Publishing;