简体   繁体   中英

Access to sharepoint 2013 site from web api

I'm working on a communication between a MVC web app developed in c# and typescript and a remote sharepoint site. I want to execute crud operations for an excel file.

I'm able to read site properties in this way:

 public async Task<string> getWebTitle(string webUrl, string usr, string psw)
        {
            //Creating Password 
            const string PWD = psw;
            const string USER = usr;
            const string RESTURL = "{0}/_api/web?$select=Title";

            //Creating Credentials 
            var passWord = new SecureString();
            foreach (var c in PWD) passWord.AppendChar(c);
            var credential = new SharePointOnlineCredentials(USER, passWord);


            //Creating Handler to allows the client to use credentials and cookie 
            using (var handler = new HttpClientHandler() { Credentials = credential })
            {
                //Getting authentication cookies 
                Uri uri = new Uri(webUrl);
                handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri));

                //Invoking REST API 
                using (var client = new HttpClient(handler))
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    HttpResponseMessage response = await client.GetAsync(string.Format(RESTURL, webUrl)).ConfigureAwait(false);
                    response.EnsureSuccessStatusCode();

                    string jsonData = await response.Content.ReadAsStringAsync();


                    return jsonData;

                }
            }
        }

jsonData object returns site properties.

How I can do to read a file, for example test.txt, saved in Documents folder in "mysite"?

Do you mean that you want to get the content of file in SharePoint?

We can use CSOM to achieve it.

Here is a sample for your reference:

    public static void getContentOfFileInDocLib(string siteUrl, string host, string sourceListName, string fileName)
    {
        siteUrl = siteUrl.EndsWith("/") ? siteUrl.Substring(0, siteUrl.Length - 1) : siteUrl;
        ClientContext context = new ClientContext(siteUrl);
        Web web = context.Site.RootWeb;

        List source = web.Lists.GetByTitle(sourceListName);

        context.Load(source);           
        context.Load(web);
        context.ExecuteQuery();

        FileCollection files = source.RootFolder.Files;
        Microsoft.SharePoint.Client.File file = files.GetByUrl(siteUrl + "/" + sourceListName + "/" + fileName);
        context.Load(file);
        context.ExecuteQuery();

        FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, file.ServerRelativeUrl);
        string filePath = host + file.ServerRelativeUrl;
        System.IO.Stream fileStream = fileInfo.Stream;
        FileCreationInformation createFile = new FileCreationInformation();
        byte[] bufferByte = new byte[1024 * 100];
        System.IO.MemoryStream memory = new System.IO.MemoryStream();
        int len = 0;
        while ((len = fileStream.Read(bufferByte, 0, bufferByte.Length)) > 0)
        {
            memory.Write(bufferByte, 0, len);
        }

        //we get the content of file here
        byte[] bytes = memory.GetBuffer();

        //do something you want
        //.......
    }

Upload file to SharePoint Document Library.

    public static void uploadFile(string siteUrl, string filePath, string fileName, string docLibName)
    {
        siteUrl = siteUrl.EndsWith("/") ? siteUrl.Substring(0, siteUrl.Length - 1) : siteUrl;           
        ClientContext context = new ClientContext(siteUrl);
        List docLib = context.Web.Lists.GetByTitle(docLibName);
        context.Load(docLib);
        context.ExecuteQuery();

        Byte[] bytes = System.IO.File.ReadAllBytes(filePath + fileName);

        FileCreationInformation createFile = new FileCreationInformation();

        createFile.Content = bytes;
        createFile.Url = siteUrl + "/" + docLibName + "/" + fileName;
        createFile.Overwrite = true;
        Microsoft.SharePoint.Client.File newFile = docLib.RootFolder.Files.Add(createFile);
        newFile.ListItemAllFields.Update();
        context.ExecuteQuery();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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