private bool UploadFileToLibrary(string FileName)
{
string filePath = "Locafilepath"; //"c:\filetobeuploaded"
string siteURL = SPContext.Current.Web.Url;
string libraryName = "DocumentLibraryName"; //internal name
SPFile spFile;
try
{
using (SPSite oSite = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
filePath = filePath.Trim()+FileName.Trim();
if (!System.IO.File.Exists(filePath))
{ throw new FileNotFoundException("File not found.", filePath);
}
// SPFolder libFolder = oWeb.GetList(libraryName).RootFolder;
SPFolder libFolder = oWeb.Folders[libraryName];
// Prepare to upload
// string fileName = System.IO.Path.GetFileName(filePath);
FileStream fileStream = File.OpenRead(filePath);
//Check the existing File out if the Library Requires CheckOut
if (libFolder.RequiresCheckout)
{
string fileUrl = string.Format("{0}/{1}/{2}", oWeb.Url, libraryName, FileName);
spFile = oWeb.GetFile(fileUrl);
if (spFile.Exists)
//spFile = libFolder.Files[fileName];
if (spFile != null)
{ spFile.CheckOut(); }
}
// Upload document
SPFile spfile = libFolder.Files.Add(FileName, fileStream, true);
// Commit
libFolder.Update();
//Check the File in and Publish a Major Version
if (libFolder.RequiresCheckout)
{
spFile = libFolder.Files[FileName];
spFile.CheckIn("Upload Comment", SPCheckinType.MajorCheckIn);
//spFile.Publish("Publish Comment");
}
}
}
}
catch (Exception ex)
{
}
return true;
}This code snippet Help to upload the file in SharePoint library.