I have written a method that reads excel files from a certain folder in SharePoint and saves them in Desktop. This is my code , but it doesn't work because I don't see the file anywhere in the Desktop of my computer.
The connection with SharePoint is made in another method.
private static void transferFile(Microsoft.SharePoint.Client.Folder fold,
ClientContext ctx,string targetPath, ref StringBuilder str, ref bool errors)
{
str.AppendLine("Folder " + fold.Name);
ctx.Load(fold.Files, f1 => f1.Include(f2 => f2.Name, f2 => f2.ListItemAllFields));
ctx.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.File file in fold.Files)
{
Dictionary<string, object> fieldsVal = file.ListItemAllFields.FieldValues;
string extension = file.Name.Substring(file.Name.Length - 4);
try
{
if (extension == "xlsx")
{
string sourceUrl = "https://mysharepoint.com" + fieldsVal["FileRef"].ToString();
int size = int.Parse(fieldsVal[System.Xml.XmlConvert.EncodeName("File Size")].ToString());
try
{
int length = 0;
int bytesRead = 0;
int chunkSize = 32 * 1024;
byte[] buffer = new byte[chunkSize];
FileInformation ffl = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fieldsVal["FileRef"].ToString());
MemoryStream stream = new MemoryStream();
while ((bytesRead = ffl.Stream.Read(buffer, 0, buffer.Length)) > 0)
{
length += bytesRead;
stream.Write(buffer, 0, bytesRead);
}
Stream streamFile = null;
string fileName;
streamFile = stream;
fileName = file.Name;
var newFileName = Path.Combine(targetPath,fileName);
var fileStream = System.IO.File.Create(newFileName);
ffl.Stream.CopyTo(fileStream);
}
catch{
}
}
catch
{
}
}
}