Download Documents from Doc library in SharePoint Online by CSOM
public void DownloadFiles()
{
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var ctx = spContext.CreateUserClientContextForSPHost())
{
Web web = ctx.Web;
Microsoft.SharePoint.Client.List list = web.Lists.GetByTitle("TestDocLibrary");
CamlQuery query = new CamlQuery();
Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(query);
ctx.Load(items);
ctx.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem listItem in items)
{
ctx.Load(listItem, i => i.File);
ctx.ExecuteQuery();
var fileRef = listItem.File.ServerRelativeUrl;
// var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileRef); // this function not working
Microsoft.SharePoint.Client.File file = listItem.File;
ClientResult<Stream> data = file.OpenBinaryStream();
ctx.Load(file);
ctx.ExecuteQuery();
int position = 1;
int bufferSize = 200000;
Byte[] readBuffer = new Byte[bufferSize];
string localFilePath = "C:\\Temp\\"+ file.Name;
using (System.IO.Stream stream = System.IO.File.Create(localFilePath))
{
while (position > 0)
{
// data.Value holds the Stream
position = data.Value.Read(readBuffer, 0, bufferSize);
stream.Write(readBuffer, 0, position);
readBuffer = new Byte[bufferSize];
}
stream.Flush();
}
}
}
}
public void DownloadFiles()
{
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var ctx = spContext.CreateUserClientContextForSPHost())
{
Web web = ctx.Web;
Microsoft.SharePoint.Client.List list = web.Lists.GetByTitle("TestDocLibrary");
CamlQuery query = new CamlQuery();
Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(query);
ctx.Load(items);
ctx.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem listItem in items)
{
ctx.Load(listItem, i => i.File);
ctx.ExecuteQuery();
var fileRef = listItem.File.ServerRelativeUrl;
// var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileRef); // this function not working
Microsoft.SharePoint.Client.File file = listItem.File;
ClientResult<Stream> data = file.OpenBinaryStream();
ctx.Load(file);
ctx.ExecuteQuery();
int position = 1;
int bufferSize = 200000;
Byte[] readBuffer = new Byte[bufferSize];
string localFilePath = "C:\\Temp\\"+ file.Name;
using (System.IO.Stream stream = System.IO.File.Create(localFilePath))
{
while (position > 0)
{
// data.Value holds the Stream
position = data.Value.Read(readBuffer, 0, bufferSize);
stream.Write(readBuffer, 0, position);
readBuffer = new Byte[bufferSize];
}
stream.Flush();
}
}
}
}
No comments:
Post a Comment