- private bool UploadFileToLibrary(string FileName)
- {
- string filePath = "D:/xxxxxx/";
- string siteURL = SPContext.Current.Web.Url;
- string libraryName = "MiscellaneousDocuments";
- 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)
- {
- sdfsdfsdfsdfdsf
- return true;
- }
This code snippet for Upload File to SharePoint Library.