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

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

Consistent SharePoint 2010 branding for Mobile browsers

Through this article I am going demonstrate you how to make consistent UI in sharepoint2010 in different mobile browsers. My mates every time asking me why we need to involve mobile device with SharePoint. Through this article I am just giving the sample where I am showing why we are slowly moving to mobiles from PC. While giving demo on "SharePoint on mobile" to client I found below things: Client want everything on their hand, means on mobile (Bcoz of busy schedule no time to open laptop/system) Client doesn't want to compromise with UI. Application should as simple and easy to use. Application should be scalable and easy to extend in future. Out of all four, below three is already provided by SharePoint. SharePoint is lacking somewhat in First point.  But as I said we developer can do anything so here we can do the same "We will bind the SharePoint without breaking SharePoint Rules". I am using safari browser for the demonstration because thro

Create Custom hit counter in SharePoint2010 using Sandbox Solution

In this blog I am going to demonstrate how to create Hit counter for SharePoint site with user details using sandbox solution. I took reference from codeplex code( http://hitcounter.codeplex.com ) which is sharepoint2007. I modified his sample and tried make it simple and easy for you. Once you understand the way I created then its very simple for you to make any further modification depends on your requirement. This solution will be very useful when you need detail about the person who visit this page and also about the number of time page view with page detail. I created this solution that will make your work easy. It's very simple where you don't need to do anything except deploying the feature and adding the web part into you master page or layout page in sharepoint2010. Below is the screenshot that will display the how it looks like: