Tuesday, March 17, 2009

To access the document in a SharePoint (MOSS) library programmatically

To access the document in a library, we need to do the following steps
1. First we need to create SPSite object for the site collection (E.g http://localhost)
2. Then we need to create SPWeb object inside the site collection (E.g http://localhost/testweb)
3. Get get the file by passing the relative url of the web (E.g /documents/samplefile.doc)
4. After getting the SPFile object, one can access the properties of the file as well as version.

Sample Code
using Microsoft.SharePoint;

SPSite site = new SPSite(http://localhost);
SPWeb spweb = site.OpenWeb("testweb");
SPFile file = spweb.GetFile("/documents/samplefile.doc");

Console.WriteLine(file.Url + ", " + file.Length);
SPFileVersionCollection versions = file.Versions;

for (int i = 1; i < versions.Count; i++)
SPFileVersion ver = versions[i];
Console.WriteLine(ver.VersionLabel + ", " + ver.Size);

No comments: