Logo

.NET CORE 传统方式调用SharePoint

photo

2025年09月25日

直接贴代码:

using Microsoft.SharePoint.Client;
using PnP.Framework;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace destlive.developer.server.Helpers
{
public class SharePointHelper
{
private static string siteUrl =AppSettingHelper.GetAppSetting(“SharePointClient:siteUrl”).ToString();
private static string userName = AppSettingHelper.GetAppSetting(“SharePointClient:userName”).ToString();
private static string userPassword = AppSettingHelper.GetAppSetting(“SharePointClient:userPassword”).ToString();
private static string clientId = AppSettingHelper.GetAppSetting(“SharePointClient:clientId”).ToString();
private static string clientSecret = AppSettingHelper.GetAppSetting(“SharePointClient:clientSecret”).ToString();
private static string domain = AppSettingHelper.GetAppSetting(“SharePointClient:domain”).ToString();
public static ClientContext GetClientContext()
{

        var authManager = new PnP.Framework.AuthenticationManager();
        var ctx = authManager.GetACSAppOnlyContext(siteUrl, clientId, clientSecret);
         if (domain.Contains("chinacloudapi"))
        ctx = authManager.GetACSAppOnlyContext(siteUrl, clientId, clientSecret, AzureEnvironment.China);

        return ctx;
    }
    private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
    {
        return true; //总是接受
    }
    public static Microsoft.SharePoint.Client.File SaveFile(string path, bool istemp = false,string docTitle= "tempDocument")
    {
        //CheckProtocol();
        //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13;
        Microsoft.SharePoint.Client.File file = null;
        using (ClientContext context = GetClientContext())
        {
            Web web = context.Web;
            string[] files = new string[1] { path };
            foreach (var localFilePath in files)
            {
                try
                {
                    string _filename = Path.GetFileName(localFilePath);
                    if (istemp)
                    {
                        _filename = "TEMP_" + Guid.NewGuid().ToString() + System.IO.Path.GetExtension(localFilePath);
                    }
                    using (FileStream fs = new FileStream(localFilePath, FileMode.Open))
                    {
                        FileCreationInformation flciNewFile = new FileCreationInformation();
                        flciNewFile.ContentStream = fs;
                        if (istemp)
                        {
                            flciNewFile.Url = _filename;
                        }
                        flciNewFile.Overwrite = true;

                        Folder folder = web.Folders.GetByUrl(siteUrl + "/" +docTitle);
                        context.Load(folder);
                        context.ExecuteQuery();
                        folder.Files.Add(flciNewFile);
                        context.ExecuteQuery();
                    }
                    file = web.GetFileByUrl(siteUrl + "/" + docTitle + "/" + _filename);
                    context.Load(file);
                    context.Load(file, f => f.ServerRelativeUrl);
                    context.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                }
            }


        }
        return file;
    }
    public static Stream GetFileStream(string uniqueId)
    {
        using (ClientContext context = GetClientContext())
        {
            Web web = context.Web;
            Microsoft.SharePoint.Client.File file = web.GetFileById(new Guid(uniqueId));
            context.Load(file);
            context.ExecuteQuery();

            // 获取文件内容
            ClientResult<Stream> fileContent = file.OpenBinaryStream();
            context.ExecuteQuery();
            Stream stream = fileContent.Value;
            Thread.Sleep(3000);
            int length = (int)stream.Length;
            return stream;      
        }
        return null;
    }

    /// <summary>
    /// 
    /// </summary>
    public static void CheckProtocol()
    {
        SecurityProtocolType securityProtocol = ServicePointManager.SecurityProtocol;

        // 检查是否设置了多个协议
        if (securityProtocol != SecurityProtocolType.Ssl3 &&
            securityProtocol != SecurityProtocolType.Tls &&
            securityProtocol != SecurityProtocolType.Tls11 &&
            securityProtocol != SecurityProtocolType.Tls12)
        {
            // 多个协议被设置,找到默认的一个
            foreach (SecurityProtocolType protocol in Enum.GetValues(typeof(SecurityProtocolType)))
            {
                if ((securityProtocol & protocol) == protocol)
                {
                    LogHelper.WriteInfo($"默认的SecurityProtocolType: {protocol}");
                    break;
                }
            }
        }
        else
        {
            // 只有一个协议被设置
            LogHelper.WriteInfo($"默认的SecurityProtocolType: {securityProtocol}");
        }
    }


    public static Stream DownFileStream(string viewPath)
    {
        Stream stream = null;
        using (ClientContext context = GetClientContext())
        {
            Web web = context.Web;
            var file = web.GetFileByServerRelativeUrl(viewPath);
            if (file != null)
            {
                Microsoft.SharePoint.Client.ClientResult<Stream> mstream = file.OpenBinaryStream();

                context.Load(file);
                context.ExecuteQuery();

                using (System.IO.FileStream localFS = System.IO.File.Open(@"D:\Sample.xlsx", FileMode.OpenOrCreate))
                {
                    mstream.Value.CopyTo(localFS);
                }
                stream = mstream.Value;
            }
        }
        return stream;
    }

    public static Microsoft.SharePoint.Client.File SaveFileStream(Stream stream, string fileName, string prefix = "TEMP_", string docTitle = "tempDocument")
    {
        //CheckProtocol();
        //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13;
        Microsoft.SharePoint.Client.File file = null;
        using (ClientContext context = GetClientContext())
        {
            Web web = context.Web;
            string _filename = prefix + Guid.NewGuid().ToString() + Path.GetExtension(fileName); ;
            try
            {
                FileCreationInformation flciNewFile = new FileCreationInformation();
                flciNewFile.ContentStream = stream;
                flciNewFile.Url = _filename;
                flciNewFile.Overwrite = true;

                Folder folder = web.Folders.GetByUrl(siteUrl + "/" + docTitle);
                context.Load(folder);
                context.ExecuteQuery();
                folder.Files.Add(flciNewFile);
                context.ExecuteQuery();
                file = web.GetFileByUrl(siteUrl + "/" + docTitle + "/" + _filename);
                context.Load(file);
                context.Load(file, f => f.ServerRelativeUrl);
                context.ExecuteQuery();
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
        }
        return file;
    }
}

}

包情况:

<ItemGroup>

	<PackageReference Include="Azure.Identity" Version="1.16.0" />
	<PackageReference Include="Microsoft.Graph" Version="5.93.0" />
	<PackageReference Include="Microsoft.SharePointOnline.CSOM" Version="16.1.26413.12010" />
	<PackageReference Include="PnP.Framework" Version="1.18.147-nightly" />
</ItemGroup>

配置节信息:

“SharePointClient”: {
“siteUrl”: “https://demo.sharepoint.com/sites/Development/demoSharePointDocument”, // 用于加密的密钥(应非常复杂)
“userName”: “admin@demo.onmicrosoft.com”, // 发行者
“userPassword”: “Passw0rd”,
“clientId”: “32bd9422-57ba-433b-aft6-03a7e37fg1q9”,
“clientSecret”: “etJUOFFfdgrgdergfd==”,
“domain”: “gloup” //chinacloudapi
}

橙子主题打折出售

其实我不卖,主要是这里是放广告的,所以就放了一个
毕竟主题都没做完,卖了也是坑.

购买它
所有附件
该文章没有附件.
本文为原创文章,请注意保留出处!

留言板

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

登录后台如下:进入Azure:选择之后进入创建应用:进入之后输入名字按照如下图示点击注册:创...Azure申请SharePoint应用

热门文章

无法握住的故土 在我们心灵最温暖的角落,总有一寸土地是属于故乡的。虽然我们看似已远离故土,可骨子里对故乡的依恋却是从未冷却过。我们无论漂泊他乡,还是在繁华都市平步青云,可故乡的悠悠情思总会潜入梦乡与你缠绵。是儿时那一缕缕茉莉的清香萦绕在梦境,也是邻家那已锈迹斑斑的铁壶里,开出艳丽的花儿在梦的边缘摇曳。故土就这样根深蒂固地在我们的灵魂深处烙下深深的印记。 作者:Pastore Antonio
1596 浏览量
EWS(Exchange Service)基本使用(获取个人会议,会议室会议内容,会议室列表,发送会议,修改会议,删除会议) 最近公司要求和exchange服务对接,所以稍微研究了一下官方文档,做出以下总结,欢迎大家补充。先...EWS(ExchangeService)基本使用(获取个人会议,会议室会议内容,会议室列表,发送会议,修改会议,删除会议) 作者:Pastore Antonio
1585 浏览量
Sql Server 部署SSIS包完成远程数据传输 本篇介绍如何使用SSIS和作业完成自动更新目标数据任务。**温馨提示:如需转载本文,请注明...SqlServer部署SSIS包完成远程数据传输 作者:Pastore Antonio
1576 浏览量
SQL Server AG集群启动不起来的临时自救大招 背景前晚一朋友遇到AG集群发生来回切换不稳定的情况,情急之下,朋友在命令行使用命令重启WSFC集群...SQLServerAG集群启动不起来的临时自救大招 作者:Pastore Antonio
1570 浏览量
windows 下安装 memcahce 官网上并未提供Memcached的Windows平台安装包,我们可以使用以下链接来下载,你需...windows下安装memcahce 作者:Pastore Antonio
1565 浏览量