Wednesday, June 10, 2009

Programmatically Upload a file from Local path to sharepoint document library [c#]

Here code is using FileUpload control to get a file from local system path.After getting this local file path ,below is code which helps to add this file to sharepoint document library.

/*Function ‘isFileExist’ use to get local file path as 'sourceFilePath' and document library path as 'targetDocumentLibraryPath' it calls function 'UploadFile' to upload sourceFile in targetDocumentLibrary.*/

public void isFileExist()
{
if(_fileUpload.HasFile)
{
string sourceFilePath = _fileUpload.PostedFile.FileName.ToString();
sourceFilePath = sourceFilePath.Replace("%20", " ");
sourceFilePath = sourceFilePath.Replace('\\', '/');
string targetDocumentLibraryPath = string.Empty;
using (SPSite osite = new SPSite(SiteURL))
{
targetDocumentLibraryPath = osite.Url + DocLibName + "/";
}
targetDocumentLibraryPath = targetDocumentLibraryPath.Replace("%20", " ");
targetDocumentLibraryPath = targetDocumentLibraryPath.Replace('\\', '/');
SPFile _File = UploadFile( _fileUpload.FileName, sourceFilePath, targetDocumentLibraryPath);
}
}

/*Function ‘UploadFile’ takes file from local system as a stream and add this stream to sharepoint document library.*/

public SPFile UploadFile(string fileName, string srcUrl, string destUrl)
{
if (!File.Exists(srcUrl))
{
throw new ArgumentException(String.Format("{0} does not exist", srcUrl), "srcUrl");
}
SPWeb site = new SPSite(destUrl).OpenWeb();
FileStream fStream = File.OpenRead(srcUrl);
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
SPFile uploadedFile = site.Folders[destUrl].Files.Add(destUrl + fileName, contents);
return uploadedFile;
}

No comments:

Post a Comment