User Tools

Site Tools


Files and Folders in SharePoint

Obtain a folder located in a library 'lib':

SPFolder folder = lib.RootFolder.SubFolders["FolderUrlName"];

Create a folder in a library 'lib':

SPFolderCollection folders = lib.RootFolder.SubFolders;
SPFolder folder = folders.Add("FolderUrl");

Obtain a file from document URL 'docUrl':

SPFile file = web.GetFile(docUrl);

Obtain the default page of an SPWeb 'web':

SPFile defaultPage = web.GetFile("default.aspx");

Add a file to a library and provide metadata:

// the 'list' variable is a library.
SPDocumentLibrary lib = list as SPDocumentLibrary;
byte[] byteArray = Encoding.ASCII.GetBytes("Some text in the file");
// Add metadata.
System.Collections.Hashtable ht = new System.Collections.Hashtable();
ht.Add("Subject", "Hey...");
ht.Add("Sender", "Miko"]);
ht.Add("To", "Kaka");
SPFile destfile = lib.RootFolder.Files.Add("MyDoc", byteArray, ht, true);

Write a string into a file associated with an SPListItem:

// 'str' is the string to write to the file.
// 'item' is an SPListItem.
Stream outStream = new MemoryStream();
byte[] outBuffer = Encoding.ASCII.GetBytes(str);
outStream.Write(outBuffer, 0, outBuffer.Length);

Move a file:

// 'item' is an SPListItem where we want to move a file to.
// 'file' is an SPFile we want to move.
string url = SPUrlUtility.CombineUrl(item.Folder.Url, file.Name);
file.MoveTo(url, true);
notes/sharepoint2010/spfile.txt · Last modified: 2016/09/26 by admin