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 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:

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
publicclassCustomWebPart : WebPart
03
{
04
protectedoverridevoidCreateChildControls()
05
{
06
LiteralControl lt = newLiteralControl();
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 (Site Action->View All Pages->Pages).

We can see the code is working fine. The next step…

Step by step BCS in SharePoint2010

Hi friends,
Through this blog I am going to share the e-Book on BCS in Sharepoint2010 which guide you in development for Business Connectivity Service in sharepoint2010.This books contains everything about BCS  with screens and real scenerio examples. Vijai Anand (Author of this e-book) have covered all possibles scenerio which required for BCS.

Below are the Contents in this e-book:

1 Business data connectivity services: an overview

2 Configure business data connectivity services
3 Configure BCS service application association