简体   繁体   English

使用 C# 从 SharePoint (CSOM) 下载特定文件

[英]Download a specific file from SharePoint (CSOM) using C#

I'm developing a C# based application that requires to download, checkout, upload, check in on a specific file from/to Sharepoint with CSOM.我正在开发一个基于 C# 的应用程序,该应用程序需要使用 CSOM 从/到 Sharepoint 下载、签出、上传、签入特定文件 So I have two questions here:所以我在这里有两个问题:

Firstly, on download, is there others way to download a specific named file under folder "Document" instead of searching through GetItemByID().首先,在下载时,是否有其他方法可以下载文件夹“Document”下的特定命名文件,而不是通过 GetItemByID() 搜索。 Please refer to code below:请参考以下代码:

string siteUrl = @"http://test.com/sites/company/";

ClientContext ctx = new ClientContext(siteUrl);
ctx.Credentials = new NetworkCredential("username", "password" , "domain");            
ctx.AuthenticationMode = ClientAuthenticationMode.Default;

var list = ctx.Web.Lists.GetByTitle("Document");
var listItem = list.GetItemById();

ctx.Load(list);
ctx.Load(listItem, i => i.File);
ctx.ExecuteQuery();

var fileRef = listItem.File.ServerRelativeUrl;
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileRef);
var fileName = Path.Combine("C:\\", (string)listItem.File.Name);

using (var fileStream = System.IO.File.Create(fileName))
{
    fileInfo.Stream.CopyTo(fileStream);
}

Secondly, in regards to the workflow (download, modify, check out, upload, check in), is this feasible of doing?其次,关于工作流程(下载、修改、签出、上传、签入),这样做可行吗?

Thanks in advance.提前致谢。

For getting specific file, no need to get ListItem by Id, instead, directly pass server relativer url like this:对于获取特定文件,不需要通过 Id 获取 ListItem,而是直接传递服务器相关者 url,如下所示:

  ClientContext clientContext = new ClientContext("http://sp/sites/dev");
    Web web = clientContext.Web;
    Microsoft.SharePoint.Client.File filetoDownload = web.GetFileByServerRelativeUrl("/sites/dev/shared%20documents/mytest.txt");
    clientContext.Load(filetoDownload);
    clientContext.ExecuteQuery();
    var fileRef = filetoDownload.ServerRelativeUrl;
    var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, fileRef);
    var fileName = Path.Combine("C:\\", (string)filetoDownload.Name);

    using (var fileStream = System.IO.File.Create(fileName))
    {
        fileInfo.Stream.CopyTo(fileStream);
    }

For other usage, checkout,update,checkin, I would suggest you can still use CSOM, as there are buit-in functions support:对于其他用法,结帐,更新,签入,我建议您仍然可以使用 CSOM,因为有内置功能支持:

File methods 文件方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM