Getting Started with SharePoint in Cloud Storage
Requirements: Cloud Storage
The SharePoint component in Cloud Storage provides an easy-to-use interface for working with files and folders in SharePoint Online sites and document libraries using the Microsoft Graph API. Capabilities include listing sites and document libraries, uploading and downloading files, creating folders, moving and copying resources, creating sharing links, strong client-side encryption, and more. This article covers the basics of using the SharePoint component, as well as how to access OneDrive for Business and SharePoint drives using the OneDrive component.
Contents
- Authorization
- Selecting a Site
- Selecting a Document Library
- Selecting Files and Folders
- Listing Files and Folders
- Uploading and Downloading Files
- Managing Files and Folders
- Using the OneDrive Component with OneDrive for Business and SharePoint
Authorization
The SharePoint component uses OAuth 2.0 for authorization. To begin, register an application with Microsoft Graph in the Azure Portal, and note its client ID and client secret. Then, configure the built-in OAuth property and call the Authorize method.
Unlike some other components, the SharePoint component does not have a default scope, so the AuthorizationScope field must be set. A common scope for the component is files.readwrite files.readwrite.all sites.readwrite.all. The component automatically adds the offline_access scope to request a refresh token.
SharePoint sharepoint = new SharePoint();
sharepoint.OAuth.ClientProfile = CloudOAuthClientProfiles.cocpApplication;
sharepoint.OAuth.GrantType = OAuthSettingsGrantTypes.cogtAuthorizationCode;
sharepoint.OAuth.ClientId = "CLIENT_ID";
sharepoint.OAuth.ClientSecret = "CLIENT_SECRET";
sharepoint.OAuth.AuthorizationScope = "files.readwrite files.readwrite.all sites.readwrite.all";
sharepoint.Authorize();
When the Authorize method is called, the component starts an embedded web server and launches a browser so the user can sign in and grant access to the application. Once access is granted, the component automatically obtains an access token and uses it in all of its requests.
The RetrieveCurrentUser method can be used to identify the account that the component is authorized as. After it is called, the CurrentUser property contains the user's ID, display name, email address, and user principal name.
sharepoint.RetrieveCurrentUser();
Console.WriteLine("Signed in as " + sharepoint.CurrentUser.DisplayName + " (" + sharepoint.CurrentUser.PrincipalName + ")");
For more information about OAuth authorization, including persisting refresh tokens, web applications, and unattended applications (using the client credentials grant type), please see our OAuth Authorization in /n software Cloud Products article.
Selecting a Site
The SiteId property selects the SharePoint site that the component works with. When SiteId is empty (the default), the component uses the root site of the authenticated user's organization.
The ListSites method lists the sites that are accessible to the authenticated user or application, and populates the Sites collection. Each site in the collection includes its Id, Name, and URL. When authenticated with delegated permissions (as a user), only the sites the user has access to are listed. When authenticated with application permissions, all of the sites in the organization can be listed.
// List the accessible sites, and select the one named "Marketing".
sharepoint.ListSites();
foreach (SharePointSite site in sharepoint.Sites) {
Console.WriteLine(site.Name + " (" + site.URL + ")");
if (site.Name == "Marketing") sharepoint.SiteId = site.Id;
}
The ListSitesParams configuration setting controls the request that ListSites makes, and can be used to search for sites or to list the subsites of a site. By default, it is set to ?search=*, which lists all accessible sites.
// List the subsites of a specific site.
sharepoint.Config("ListSitesParams=/" + parentSiteId + "/sites");
sharepoint.ListSites();
Selecting a Document Library
Each SharePoint site contains one or more document libraries, which hold the site's files and folders. The DocumentLibrary property selects the document library that the component works with. When DocumentLibrary is empty (the default), the component uses the default document library of the site selected by SiteId.
The ListDocumentLibraries method lists the document libraries in the selected site, and populates the DocumentLibraries collection. Each document library in the collection includes its Id, Name, and Description, as well as storage information such as TotalSpace, UsedSpace, and RemainingSpace. If there are more results than fit in a single page, the DocumentLibraryMarker property will be populated. Continue calling ListDocumentLibraries until DocumentLibraryMarker is empty to accumulate all pages of results in the DocumentLibraries collection.
// List the document libraries in the selected site, and select the one named "Documents".
do {
sharepoint.ListDocumentLibraries();
} while (!string.IsNullOrEmpty(sharepoint.DocumentLibraryMarker));
foreach (SharePointDocumentLibrary library in sharepoint.DocumentLibraries) {
Console.WriteLine(library.Name + ": " + library.UsedSpace + " of " + library.TotalSpace + " bytes used");
if (library.Name == "Documents") sharepoint.DocumentLibrary = library.Id;
}
The GetDocumentLibraryInfo method retrieves information about only the currently selected document library.
Selecting Files and Folders
Most methods operate on the file or folder currently selected by the RemoteId or RemotePath property. RemoteId selects a resource by its ID, while RemotePath selects a resource by its path within the document library (e.g., /Reports/2026/summary.pdf). If both properties are set, RemoteId is used. When both properties are empty, methods that operate on folders use the root folder of the selected document library.
The selected resource must be in the document library currently selected by the DocumentLibrary property.
Listing Files and Folders
The ListResources method lists the files and folders within the selected folder, and populates the Resources collection. Each resource in the collection includes fields such as Id, Name, Path, ResourceType, Size, ModifiedTime, and WebURL. If there are more results than fit in a single page, the ResourceMarker property will be populated. Continue calling ListResources until ResourceMarker is empty to accumulate all pages of results in the Resources collection.
// List the contents of the "Reports" folder.
sharepoint.RemotePath = "/Reports";
do {
sharepoint.ListResources();
} while (!string.IsNullOrEmpty(sharepoint.ResourceMarker));
foreach (SharePointResource resource in sharepoint.Resources) {
string type = resource.ResourceType == SharePointResourceTypes.sprtFolder ? "Folder" : "File";
Console.WriteLine(type + ": " + resource.Name + " (" + resource.Size + " bytes)");
}
The Search method can also be used to search for resources within the selected folder that match a query.
Uploading and Downloading Files
The UploadFile method uploads a new file to the selected folder. Its only parameter is the name of the new file, and it returns the ID of the uploaded file. The data to upload is taken from the stream set with SetUploadStream if one is set, from the file specified by LocalFile if it is set, or otherwise from the ResourceData property.
// Upload a file to the "Reports" folder.
sharepoint.RemotePath = "/Reports";
sharepoint.LocalFile = "C:\\reports\\summary.pdf";
string fileId = sharepoint.UploadFile("summary.pdf");
By default, the file is uploaded in a single request. For large files, set the UseResumableUpload property to true to upload the file in fragments, which allows an interrupted upload to be resumed.
The DownloadFile method downloads the selected file. The data is written to the stream set with SetDownloadStream if one is set, to the file specified by LocalFile if it is set, or otherwise to the ResourceData property.
// Download the file that was just uploaded.
sharepoint.RemoteId = fileId;
sharepoint.LocalFile = "C:\\downloads\\summary.pdf";
sharepoint.DownloadFile();
To encrypt files before uploading them and decrypt them after downloading them, set the EncryptionPassword property. For more information, please see our Enabling Client-Side Encryption in Cloud Storage entry.
Managing Files and Folders
The SharePoint component also provides methods for organizing the files and folders in a document library. Each of these methods operates on the resource selected by RemoteId or RemotePath:
- CreateFolder creates a new folder within the selected folder, and returns its ID.
- DeleteResource deletes the selected file or folder.
- MoveResource moves the selected resource to the folder with the specified ID. The special ID root refers to the root folder of the document library.
- CopyResource copies the selected resource to the specified folder, with an optional new name.
- CreateLink creates a sharing link for the selected resource, which can be read-only or allow editing.
// Create a folder in the root of the document library.
sharepoint.RemoteId = "";
sharepoint.RemotePath = "";
string archiveId = sharepoint.CreateFolder("Archive");
// Move a file into the new folder.
sharepoint.RemotePath = "/Reports/summary.pdf";
sharepoint.MoveResource(archiveId);
// Create a read-only sharing link for the moved file.
sharepoint.RemotePath = "/Archive/summary.pdf";
string link = sharepoint.CreateLink(true);
Copy operations run asynchronously on the server. After calling CopyResource, use the PollCopyStatus method to check the progress of the copy, which populates the CopyStatus, CopyPercentDone, and (once the copy completes) CopiedResourceId properties.
// Copy a file into the "Archive" folder with a new name, and wait for the copy to complete.
sharepoint.RemotePath = "/Archive/summary.pdf";
sharepoint.CopyResource(archiveId, "summary-copy.pdf");
do {
System.Threading.Thread.Sleep(1000);
sharepoint.PollCopyStatus();
} while (sharepoint.CopyStatus != "completed" && sharepoint.CopyStatus != "failed");
Console.WriteLine("Copied resource ID: " + sharepoint.CopiedResourceId);
The component also supports change tracking with the ListChanges method, and resumable uploads and downloads. Refer to the component documentation for more information.
Using the OneDrive Component with OneDrive for Business and SharePoint
The OneDrive component can also access OneDrive for Business drives and SharePoint document libraries, which Microsoft Graph refers to as drives. This is useful for applications that work with both OneDrive and SharePoint, or that need to access the drives owned by a Microsoft 365 group.
By default, the OneDrive component uses the authenticated user's default drive. To use a different drive, set the Drive property to the ID of the drive. The ListDrives method lists the available drives and populates the Drives collection, and the ListDrivesScope configuration setting controls which drives are listed:
- 0 (default) lists the current user's drives.
- 1 lists the drives owned by the group specified by the GroupId configuration setting, or by the user's organization if GroupId is empty.
- 2 lists the drives owned by the SharePoint site specified by the SiteId configuration setting, or by the organization's root site if SiteId is empty.
Each drive in the Drives collection includes its Id, Name, DriveType (personal, business, or document library), and storage information.
OneDrive onedrive = new OneDrive();
onedrive.OAuth.ClientId = "CLIENT_ID";
onedrive.OAuth.ClientSecret = "CLIENT_SECRET";
onedrive.OAuth.AuthorizationScope = "files.readwrite files.readwrite.all sites.readwrite.all";
onedrive.Authorize();
// List the drives (document libraries) of a SharePoint site.
onedrive.Config("ListDrivesScope=2");
onedrive.Config("SiteId=SITE_ID");
do {
onedrive.ListDrives();
} while (!string.IsNullOrEmpty(onedrive.DriveMarker));
foreach (OneDriveDrive drive in onedrive.Drives) {
Console.WriteLine(drive.Name + " (" + drive.DriveType + ")");
}
// Select the first drive, and list its root folder.
onedrive.Drive = onedrive.Drives[0].Id;
onedrive.ListResources();
When the Drive property is empty, the GroupId and SiteId configuration settings can also be used on their own to select the default drive of a group or site. The UsersGroups and SubSites configuration settings can be queried to get the IDs of the user's groups and of a site's subsites, respectively. Note that these drive-related features are only available for work or school accounts, and are not supported for personal Microsoft accounts.
For applications that mainly work with SharePoint sites and document libraries, the SharePoint component provides a more direct interface, including the ListSites and ListDocumentLibraries methods described above.
We appreciate your feedback. If you have any questions, comments, or suggestions about this article please contact our support team at support@nsoftware.com.