[英]Get a list of files from Sharepoint and download the latest file
我正在嘗試從 SharePoint 位置獲取文件列表,然后使用 C# 獲取最新的(按創建時間)文件。
可用資源討論 SPWeb/SPSite,但這些資源不能直接在 Visual Studio 2013 上使用;
SharePoint 站點: https://sharepoint.amr.<Website>.com/sites/OrganizationName/Group/Shared Documents/Reports/Area/
到目前為止,我一直無法這樣做。
任何人都可以提供一些有用的資源或示例嗎?
如果您不在 SharePoint 服務器上運行代碼,則需要使用客戶端對象模型。
使用 SharePoint 2013 客戶端庫代碼完成基本操作
我相信只要您可以訪問 url,這應該針對 SharePoint 運行。 我在我的 Office 365 上運行了這個,並且有效。 我必須再次對 Office 365 進行身份驗證,但如果您的 AD 用戶有權訪問該庫,您可能可以跳過該步驟。
SharePoint 2013:在 Office 365 中對 .NET 客戶端對象模型進行身份驗證
// Url to site
string url = "https://your.sharepoint.com";
// get context for that Url
var ctx = new ClientContext(url);
// Provide credentials
// (Might be able to skip this if the server is on prem and your
// AD user has permissions to access the library)
var password = new SecureString();
foreach (var c in "your_password".ToCharArray())
password.AppendChar(c);
ctx.Credentials =
new SharePointOnlineCredentials("login@your.onmicrosoft.com", password);
// get the library
var list = ctx.Web.GetList("/Shared%20Documents/");
// Empty query to get all items
var listItems = list.GetItems(new CamlQuery());
// Load all items and use Include to specify what properties
// we want to be able to access
ctx.Load(listItems,
items => items.Include(
item => item["Created"],
item => item.File));
// Execute the query
ctx.ExecuteQuery();
// Just to show you we have all the items now
foreach (var item in listItems)
{
Console.WriteLine("{0} - {1}",
item["Created"],
item.File.ServerRelativeUrl);
}
// Orderby something and take one
var fileInfo = listItems
.OrderBy(x => x.File.Name)
.Take(1)
.FirstOrDefault();
if (fileInfo != null)
{
// Open file
var fileInformation =
File.OpenBinaryDirect(ctx, fileInfo.File.ServerRelativeUrl);
// Save File to c:\temp
using (var fileStream =
new FileStream(@"c:\temp\" + fileInfo.File.Name, FileMode.Create))
fileInformation.Stream.CopyTo(fileStream);
}
以及保存從這里獲取的流的擴展
// Extension to save stream
public static void CopyTo(this System.IO.Stream src, System.IO.Stream dest)
{
if (src == null)
throw new System.ArgumentNullException("src");
if (dest == null)
throw new System.ArgumentNullException("dest");
System.Diagnostics.Debug.Assert(src.CanRead, "src.CanRead");
System.Diagnostics.Debug.Assert(dest.CanWrite, "dest.CanWrite");
int readCount;
var buffer = new byte[8192];
while ((readCount = src.Read(buffer, 0, buffer.Length)) != 0)
dest.Write(buffer, 0, readCount);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.