Hi all, here I want describe two function that use the SharePoint Client Object Model:
- to download a file from a SharePoint website to a local path;
- to upload a file from a local path to a SharePoint website.
public static bool DownloadFile(ClientContext context, string fileRelativeUrl, string destinationPath, string fileName)
{
try
{
fileRelativeUrl = fileRelativeUrl.Replace("/Images/","/PublishingImages/");
string sourceUrl = fileRelativeUrl + fileName;
string completeDestinationPath=destinationPath + fileName;
if (!System.IO.File.Exists(completeDestinationPath))
{
Directory.CreateDirectory(destinationPath);
FileInformation spFileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, sourceUrl);
using (Stream destination = System.IO.File.Create(completeDestinationPath))
{
for (int a = spFileInfo.Stream.ReadByte(); a != -1; a = spFileInfo.Stream.ReadByte())
destination.WriteByte((byte)a);
}
}
}
catch (Exception ex)
{
Logger.WriteLog(string.Format("Error during copying file: {0} with error {1}", fileRelativeUrl, ex.StackTrace));
return false;
}
return true;
}
public static void UploadFile(Web currWeb, string destRelativeUrl, string file, ClientContext destContext)
{
try
{
Microsoft.SharePoint.Client.File destFile = currWeb.GetFileByServerRelativeUrl(destRelativeUrl);
bool bExists = false;
try
{
destContext.Load(destFile);
destContext.ExecuteQuery(); //Raises exception if the file doesn't exist
bExists = destFile.Exists; //may not be needed - here for good measure
Logger.WriteLog(string.Format("File already exist: {0}", destRelativeUrl));
}
catch
{
}
if (!bExists)
{
using (FileStream fs = new FileStream(file, FileMode.Open))
{
Microsoft.SharePoint.Client.File.SaveBinaryDirect(destContext, destRelativeUrl, fs, false);
Logger.WriteLog(string.Format("File copied: {0}", destRelativeUrl));
}
}
}
catch (Exception ex)
{
Logger.WriteLog(string.Format("Error during upload file: {0} with error {1}", file, ex));
}
}
Here a wiki to help to use the SharePoint Client Object Model.