It often happens that you have to create and save a file in Sharepoint from Dynamics 365 FO. Below is a method that, taking the file stream and filename as input, allows you to save this file in a specific Sharepoint folder.
/// <summary>
/// Save file in specific Sharepoint folder
/// </summary>
/// <param name = "_stream">Stream of the file</param>
/// <param name = "_filename">Filename</param>
public void saveFile(System.IO.MemoryStream _stream, Filename _filename)
{
/* Example */
str site = '/sites/OneERPEnvisioningProject';
str folder = 'Documenti condivisi/Master Data/Test';
System.UriBuilder builder = new System.UriBuilder('orgname.sharepoint.com');
str host = builder.Host;
str extId = xUserInfo::getCurrentUserExternalId();
Microsoft.Dynamics.AX.Framework.FileManagement.SharePointDocumentStorageProvider storageProvider = new Microsoft.Dynamics.AX.Framework.FileManagement.SharePointDocumentStorageProvider('orgname.sharepoint.com', site, folder, extId);
storageProvider.ProviderId = DocuStorageProviderType::SharePoint;
_stream.Position = 0;
boolean fileExists;
fileExists = storageProvider.FileExists(_filename);
if(fileExists)
{
if(_stream.Length > 0 )
{
storageProvider.SaveFileWithOverwrite(newGuid(), _filename, 'application/csv', _stream);
}
}
else
{
if(_stream.Length > 0 )
{
storageProvider.SaveFile(newGuid(), _filename, 'application/csv', _stream);
}
}
}