Sharepoint Document Library - SPDocumentLibrary Related Code

 Submit a document and its related metadata into a document library
  • Get reference to the Document Libraray and the folder.
SPList objList = web.Lists["CustomDocLibrary"];
SPDocumentLibrary objLib = (SPDocumentLibrary)objList;
SPFolder rFolder = objLib.RootFolder;
SPFile objFile;

// GET ARRAY INSTANCE OF THE FILE TO BE UPLOADED from FileUpload web control
byte[] byteArr = FileUploadToDoc.FileBytes;
string urlOfFile = rFolder.Url + "/" + FileUploadToDoc.FileName;

// GET THE METADATA. HERE “REQUESTOR” AND “TAXFORM” ARE THE COLUMNS THAT WOULD HOLD THE METADATA VALUE.
Hashtable metaData = new Hashtable();
metaData.Add("Requestor", txtRequestor.Text);
metaData.Add("TaxForm", txtTaxForm.Text);

objFile = rFolder.Files.Add(urlOfFile, byteArr, metaData, true);
objFile.Update();
  •  Retrieve a document from the document library and open and read  using hyperlink
SPListItemCollection items = web.Lists["CustomDocLibrary"].Items;
SPListItem item = items.GetItemById(requestID);
SPFile file = item.File;
fileInDocLibUrl = web.Url+ "/" + file.Url;
LinkToDocOnBrowser.Text = file.Name.ToString();
LinkToDocOnBrowser.NavigateUrl = fileInDocLibUrl;

  • Open the document using “OPEN SAVE CANCEL DIALOG BOX”.
Write the following code in the click event of the “linkbutton”, to open the “Open save cancvel” dialog box.
SPListItemCollection items = web.Lists["CustomDocLibrary"].Items;
SPListItem item = items.GetItemById(requestID);
SPFile file = item.File;
string   Url = web.Url+ "/" + file.Url;
SPFile file = web.GetFile(Url);
byte[] obj = (byte[])file.OpenBinary();
Response.ClearContent();
Response.ClearHeaders();
Response.AppendHeader("Content-Disposition", "attachment; filename= " + file.Name.ToString());
Response.ContentType = "application/octet-stream";
//Check that the client is connected and has not closed the connection after the request
if (Response.IsClientConnected)
{ Response.BinaryWrite(obj); }
Response.Flush();
Response.Close();

1 comment:

Anonymous said...

Very helpful. Thanks.