I wanted to fetch all files from the document library one of my Online Sharepoint site. For that, I have created 2 apps i.e. Console App and ASP.Net MVC apps
Below is the code,
using ASPNetDemo.Models;
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Web.Mvc;
namespace ASPNetDemo.Controllers
{
public class DocumentLibraryController : Controller
{
private readonly string baseURL;
private readonly string siteURL;
public DocumentLibraryController()
{
baseURL = "https://onevirtualoffice.sharepoint.com";
siteURL = $"{baseURL}/sites/mysite";
}
// GET: DocumentLibrary
public ActionResult Index()
{
var model = new FileUploadViewModel();
model.Username = "[email protected]";
model.Password = "{password}";
var list = GetFiles(model);// get all files from
return View();
}
public List<string> GetFiles(FileUploadViewModel model)
{
try
{
using (var clientContext = new ClientContext(siteURL))
{
SecureString passWordSecure = new SecureString();
foreach (char c in model.Password.ToCharArray()) passWordSecure.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials(model.Username, passWordSecure);
Web web = clientContext.Web;
#region get list
List<string> fileList = new List<string>();
var results = new Dictionary<string, IEnumerable<Microsoft.SharePoint.Client.File>>();
var lists = clientContext.LoadQuery(clientContext.Web.Lists.Where(l => l.BaseType == BaseType.DocumentLibrary));
clientContext.ExecuteQuery();
foreach (var list in lists)
{
if (list.Title.Equals("TestFolder"))
{
var items = list.GetItems(CreateAllFilesQuery());
clientContext.Load(items, icol => icol.Include(i => i.File));
results[list.Title] = items.Select(i => i.File);
}
}
clientContext.ExecuteQuery();
foreach (var result in results)
{
foreach (var file in result.Value)
{
var fileName = "";
if (string.IsNullOrEmpty(file.LinkingUri))
fileName = string.Concat(baseURL, file.ServerRelativeUrl);
else
fileName = file.LinkingUri;
fileList.Add(fileName);
}
}
return fileList;
#endregion
}
}
catch (Exception ex)
{
throw ex;
}
}
private CamlQuery CreateAllFilesQuery()
{
var qry = new CamlQuery();
qry.ViewXml = "<View Scope=\"RecursiveAll\"><Query><Where><Eq><FieldRef Name=\"FSObjType\" /><Value Type=\"Integer\">0</Value></Eq></Where></Query></View>";
return qry;
}
}
}
The above code is working fine in Console application and its fetching all the files under TestFolder document library. But When I tried the same code in ASP.Net MVC5 Framework 4.6.1 then it throwing an exception as The sign-in name or password does not match one in the Microsoft account system.
Could you please help to guide where I am wrong.