How to Scan Files in SharePoint Online Site Drive with C#
The availability of affordable cloud storage solutions like SharePoint Online Site Drive has made it drastically easier for small businesses and individual developers to accommodate direct file uploads from client-side users. Naturally, however, this availability has also increased the likelihood that cyber-attacks will target vulnerabilities in cloud storage to inject viruses, ransomware, spyware, and dozens of other content-based threats.
Thankfully, you can scan files in your SharePoint Online Site Drive for free (up to 800 times per month) by integrating the Advanced Virus Scanning API provided below with ready-to-run C# code examples. This API offers 360-degree content protection against viruses and malware (including spyware, ransomware trojans, etc.), executables, invalid files, scripts, and much more. It also allows you to customize restrictions on file types by whitelisting file extensions in the API request body.
To get this set up with your SharePoint instance, you’ll need the following SharePoint information:
- Client ID (retrievable from the Azure Active Directory portal)
- Client Secret (retrievable from the Azure Active Directory portal)
- SharePoint Domain Name (i.e., mydomain.sharepoint.com)
- Site ID (GUID of the SharePoint site you wish to retrieve the file from)
- Tenant ID (optional; tenant ID of your Azure Active Directory)
In addition, you’ll need to grab a free-tier API key by registering a free account on the Cloudmersive website.
Once you’ve collected all the above information, you can install the client SDK via NuGet by running this command in the Packet Manager console:
Install-Package Cloudmersive.APIClient.NET.VirusScan -Version 3.0.4
After that, you can copy in the below code to structure your API call.
To allow scripts, executables, invalid files, or configure any other custom threat rule, simply change the default Boolean value from “true” to “false”. In order to set custom file restrictions, supply your whitelist of file extensions in comma separated format (you can follow the example in the code comments).
using System;
using System.Diagnostics;
using Cloudmersive.APIClient.NET.VirusScan.Api;
using Cloudmersive.APIClient.NET.VirusScan.Client;
using Cloudmersive.APIClient.NET.VirusScan.Model;
namespace Example
{
public class ScanCloudStorageScanSharePointOnlineFileAdvancedExample
{
public void main()
{
// Configure API key authorization: Apikey
Configuration.Default.AddApiKey("Apikey", "YOUR_API_KEY");
var apiInstance = new ScanCloudStorageApi();
var clientID = clientID_example; // string | Client ID access credentials; see description above for instructions on how to get the Client ID from the Azure Active Directory portal.
var clientSecret = clientSecret_example; // string | Client Secret access credentials; see description above for instructions on how to get the Client Secret from the Azure Active Directory portal
var sharepointDomainName = sharepointDomainName_example; // string | SharePoint Online domain name, such as mydomain.sharepoint.com
var siteID = siteID_example; // string | Site ID (GUID) of the SharePoint site you wish to retrieve the file from
var tenantID = tenantID_example; // string | Optional; Tenant ID of your Azure Active Directory (optional)
var filePath = filePath_example; // string | Path to the file within the drive, such as 'hello.pdf' or '/folder/subfolder/world.pdf'. If the file path contains Unicode characters, you must base64 encode the file path and prepend it with 'base64:', such as: 'base64:6ZWV6ZWV6ZWV6ZWV6ZWV6ZWV'. (optional)
var itemID = itemID_example; // string | SharePoint itemID, such as a DriveItem Id (optional)
var allowExecutables = true; // bool? | Set to false to block executable files (program code) from being allowed in the input file. Default is false (recommended). (optional)
var allowInvalidFiles = true; // bool? | Set to false to block invalid files, such as a PDF file that is not really a valid PDF file, or a Word Document that is not a valid Word Document. Default is false (recommended). (optional)
var allowScripts = true; // bool? | Set to false to block script files, such as a PHP files, Python scripts, and other malicious content or security threats that can be embedded in the file. Set to true to allow these file types. Default is false (recommended). (optional)
var allowPasswordProtectedFiles = true; // bool? | Set to false to block password protected and encrypted files, such as encrypted zip and rar files, and other files that seek to circumvent scanning through passwords. Set to true to allow these file types. Default is false (recommended). (optional)
var allowMacros = true; // bool? | Set to false to block macros and other threats embedded in document files, such as Word, Excel and PowerPoint embedded Macros, and other files that contain embedded content threats. Set to true to allow these file types. Default is false (recommended). (optional)
var allowXmlExternalEntities = true; // bool? | Set to false to block XML External Entities and other threats embedded in XML files, and other files that contain embedded content threats. Set to true to allow these file types. Default is false (recommended). (optional)
var restrictFileTypes = restrictFileTypes_example; // string | Specify a restricted set of file formats to allow as clean as a comma-separated list of file formats, such as .pdf,.docx,.png would allow only PDF, PNG and Word document files. All files must pass content verification against this list of file formats, if they do not, then the result will be returned as CleanResult=false. Set restrictFileTypes parameter to null or empty string to disable; default is disabled. (optional)
try
{
// Advanced Virus Scan a file in a SharePoint Online Site Drive
CloudStorageAdvancedVirusScanResult result = apiInstance.ScanCloudStorageScanSharePointOnlineFileAdvanced(clientID, clientSecret, sharepointDomainName, siteID, tenantID, filePath, itemID, allowExecutables, allowInvalidFiles, allowScripts, allowPasswordProtectedFiles, allowMacros, allowXmlExternalEntities, restrictFileTypes);
Debug.WriteLine(result);
}
catch (Exception e)
{
Debug.Print("Exception when calling ScanCloudStorageApi.ScanCloudStorageScanSharePointOnlineFileAdvanced: " + e.Message );
}
}
}
}
Keep in mind that all file uploads will be validated & verified against the custom file restriction rules (if you choose to create a whitelist). Any file uploads with extensions NOT represented on this list will automatically receive a CleanResult: False response from the API.
You can review the JSON example below to get a sense for what a full response body will look like:
{
"Successful": true,
"CleanResult": true,
"ContainsExecutable": true,
"ContainsInvalidFile": true,
"ContainsScript": true,
"ContainsPasswordProtectedFile": true,
"ContainsRestrictedFileFormat": true,
"ContainsMacros": true,
"VerifiedFileFormat": "string",
"FoundViruses": [
{
"FileName": "string",
"VirusName": "string"
}
],
"ErrorDetailedDescription": "string",
"FileSize": 0,
"ContentInformation": {
"ContainsJSON": true,
"ContainsXML": true,
"ContainsImage": true,
"RelevantSubfileName": "string"
}
}