Pages

Monday 5 September 2011

Document Libraries

Document libraries are lists that handle documents. Other than the attachments, which are stored in the containing web’s central attachment library, a document library stores its files directly. The programmatic access to libraries is similar to lists. In addition to list-related functions, you use streams, such as a MemoryStream, when saving or loading files.

Reading a File from the Shared Documents Library

Each site contains a library called Shared Documents. Code shown next explains how to retrieve a file as an SPFile object.

using (SPSite site = new SPSite("http://sharepointserve"))
{
using (SPWeb web = site.OpenWeb())
{
if (web.GetFolder("Shared Documents").Exists)
{
SPFolder folder = web.GetFolder("Shared Documents");
SPFile file = folder.Files["WordTemplate.docx"];
}
}
}

Adding a Folder to a Library

If you work with folders, your users might not be satisfied with the UI support. For greater capability, you can create a function that adds folders programmatically.

using (SPSite site = new SPSite("http://sharepointserve"))
{
using (SPWeb web = site.OpenWeb())
{
SPList lib = web.Lists["Shared Documents"];
SPFolder parent = lib.RootFolder;
SPFolder child = parent.SubFolders.Add("SubFolderName");
parent.Update();
}
}

This code adds a SubFolderName folder to the library’s root.

Saving Data to Libraries

To upload a file to a library, you use a similar approach (see Listing 4-21). The file must be available as a Stream or a byte array.

using (SPSite site = new SPSite("http://sharepointserve"))
{
using (SPWeb web = site.OpenWeb())
{
spweb.AllowUnsafeUpdates = true;

SPFolder folder = web.Folders[site.URL + "/Shared Documents/"];
byte[] content = null;
using (FileStream filestream = new FileStream(@"C:\Sample.docx",
System.IO.FileMode.Open))
{
content = new byte[(int) filestream.Length];
filestream.Read(content, 0, (int) filestream.Length);
filestream.Close();
}

SPFile file = folder.Files.Add("Sample.docx", content, true);
// do something usefil with file
}
}

You can add the file to a specific folder:

SPFile file = folder.SubFolders["SubFolder"].Files.Add("Sample.docx",
content,
true);

The content variable is the same as shown previously.

No comments:

Post a Comment

Popular Posts