I am having issues saving a Sharepoint filecollection of picture to a local directory. I am very new with Sharepoint 2016 and I am having issues resolving this issue. Seems like when I run this code it makes a first pass to give me the first image of my file collection. However when I look into the intended directory the image is 0 bytes(Just an empty file). After it stays running for a little while it throws the following exception error.
Error:
Additional information: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
public static void ImageRetrival(DHG.OneDrive.Helpers.OneDriveHelper oneDrive, string user)
{
try
{
var wb = userContext.Web;
userContext.Load(wb);
var files = oneDrive.GetOneDriveFilesByFolderName(user);
var test = Microsoft.SharePoint.Client.File.OpenBinaryDirect(userContext, wb.ServerRelativeUrl);
FileStream fs = null;
if (files != null)
{
foreach (var file in files)
{
var fileName = file.Name.ToString();
string path = @"C:\Top-Level\" + fileName;
fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
test.Stream.CopyTo(fs);
}
}
}
catch (Exception e)
{
throw e;
}
}
Ok figured it out, logic was wrong I had the following line outside my for each loops which was making it empty when I was calling it back in for each code. This was the reason my file was coming up as 0 Bytes.
Corrected Code
public static void ImageRetrival(PHG.OneDrive.Helpers.OneDriveHelper oneDrive, string user)
{
try
{
var wb = userContext.Web;
userContext.Load(wb);
var files = oneDrive.GetOneDriveFilesByFolderName(user);
if (files != null)
{
foreach (var file in files)
{
// has to be inside my foreach loop referencing file in files which represents a sharepoint filecollection
var fileinfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(userContext, file.ServerRelativeUrl);
var fileName = file.Name.ToString();
string path = @"C:\Top-Level\" + fileName;
using (var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
fileinfo.Stream.CopyTo(fs);
}
}
}
}
catch (Exception e)
{
throw e;
}
}