In this article, I am going show
how to Upload/Download document through code to a SharePoint document
library. I am going to use SharePoint object model and refer the this A1, A2
articles for more information.Here is the sample
code;
Upload Document
private void UploadDocument(){try{this.Cursor = Cursors.WaitCursor;string currentLibName = LibraryName;string SelectedfilePath = FilePath;bool overWrite = ISOverWrite;SPSite Site = new SPSite(URL);using (SPWeb web = Site.OpenWeb()){if (!System.IO.File.Exists(SelectedfilePath))throw new FileNotFoundException("File not found.", SelectedfilePath);SPFolder libFolder = web.Folders[currentLibName];// Prepare to uploadstring fileName = System.IO.Path.GetFileName(SelectedfilePath);FileStream fileStream = File.OpenRead(SelectedfilePath);//Check the existing File out if the Library Requires CheckOutif (libFolder.RequiresCheckout){try{SPFile fileOld = libFolder.Files[fileName];fileOld.CheckOut();}catch { }}// Upload documentSPFile spfile = libFolder.Files.Add(fileName, fileStream, overWrite);libFolder.Update();MessageBox.Show("File has successfully uploaded.", "Message");try{fileStream.Close();}catch (Exception) { }}this.Cursor = Cursors.Default;}catch (Exception ex){MessageBox.Show(ex.Message, "Message");return; ;}
Download Document
void DownloadDocument(){try{SPSite Site = new SPSite(URL);string filePath = filePath;string DocLib = LibraryName;int docID = DocumentID;using (SPWeb web = Site.OpenWeb()){SPList Selectedlist = web.Lists[DocLib];SPListItem item = Selectedlist.GetItemById(docID);byte[] binfile = item.File.OpenBinary();FileStream fstream = new FileStream(filePath + "\\" + item.File.Name,FileMode.Create, FileAccess.ReadWrite);fstream.Write(binfile, 0, binfile.Length);fstream.Close();MessageBox.Show("Document has successfully saved.", "Message");}}catch (Exception ex){MessageBox.Show(ex.Message, "Message");return;}}
where i can write DownloadDocument event in sharepoint c# webpart
ReplyDelete