You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过C#控制台程序上传文件至共享OneDrive?遇连接错误求助

问题:C#控制台程序无法上传文件至共享OneDrive

我一直无法通过C#控制台程序将一组文件上传至共享OneDrive,尝试多种方案均未奏效,怀疑初始思路有误。

共享OneDrive链接:
https://insertorganization-my.sharepoint.com/personal/name_organization_com/_layouts/15/onedrive.aspx?id=%2Fsites%2Forganization%2FShared%20Documents%2FGeneral%2F%5Fname&listurl=https%3A%2F%2Forganizationna%2Esharepoint%2Ecom%2Fsites%2Forganization%2FShared%20Documents&viewid=someidview=0

我使用如下代码上传文件,但持续抛出错误:

Microsoft.SharePoint.Client.ClientRequestException: Cannot contact site at the specified URL...
at Microsoft.SharePoint.Client.ClientContext.GetFormDigestInfo(WebRequestExecutor executor)
at Microsoft.SharePoint.Client.ClientContext.GetFormDigestInfoPrivate()
at Microsoft.SharePoint.Client.ClientContext.EnsureFormDigest()
at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()
at API_Calls.ACH_Upload() in filepath:line 70

代码示例

public class API_Calls
{
    public static void ACH_Upload()
    {
        try
        {
            string userName = "username";
            string password = "password";
            var securePassword = new SecureString();

            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }

            using (var ctx = new ClientContext("OneDrive_Url"))
            {
                ctx.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(userName, securePassword);
                Web web = ctx.Web;
                ctx.Load(web);
                ctx.ExecuteQuery();
                FileCreationInformation newFile = new FileCreationInformation();
                newFile.Content = System.IO.File.ReadAllBytes(@"C:\Data\ACH_Files\ACH_" + DateTime.Now.ToString("MM_dd_yyyy") + @"\" + DateTime.Now.ToString("MM_dd_yyyy") + @"_ACH_organization.xlsx");
                newFile.Url = DateTime.Now.ToString("MM_dd_yyyy") + @"_ACH_organization.xlsx";
                List byTitle = ctx.Web.Lists.GetByTitle("ACH_" + DateTime.Now.ToString("MM_dd_yyyy"));
                Folder folder = byTitle.RootFolder.Folders.GetByUrl("_developmentfoldername");
                ctx.Load(folder);
                ctx.ExecuteQuery();
                Microsoft.SharePoint.Client.File uploadFile = folder.Files.Add(newFile);
                ctx.Load(byTitle);
                ctx.Load(uploadFile);
                ctx.ExecuteQuery();
                Console.WriteLine("done");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
 }
}

我期望程序读取本地文件夹中的文件并上传至共享OneDrive内指定文件夹,但未能成功。请问当前方案是否正确,或需调整方向?


解决方案

你的核心问题出在ClientContext的URL配置错误,以及对共享OneDrive(实际是SharePoint站点文档库)的访问逻辑有误,以下是具体修正步骤:

1. 修正ClientContext的站点URL

你当前使用的OneDrive_Url是网页端的跳转链接,并非SharePoint站点的根URL。从你提供的共享链接中,正确的站点根URL应为:
https://organizationna.sharepoint.com/sites/organization
必须用这个地址初始化ClientContext,否则无法建立有效连接。

2. 调整文档库与文件夹的访问逻辑

代码中通过Lists.GetByTitle获取列表的方式错误,共享OneDrive的"Shared Documents"是一个文档库,对应的列表标题是**"Shared Documents"**,而非你拼接的ACH_日期。正确的访问路径应该是:

  • 先获取"Shared Documents"文档库
  • 再定位到目标子文件夹(根据共享链接路径:General/_name/_developmentfoldername)

修正后的核心代码片段:

// 替换为正确的SharePoint站点URL
using (var ctx = new ClientContext("https://organizationna.sharepoint.com/sites/organization"))
{
    ctx.Credentials = new SharePointOnlineCredentials(userName, securePassword);
    
    // 获取Shared Documents文档库
    List docLib = ctx.Web.Lists.GetByTitle("Shared Documents");
    ctx.Load(docLib.RootFolder);
    ctx.ExecuteQuery();

    // 定位到目标文件夹
    Folder targetFolder = docLib.RootFolder.Folders.GetByUrl("General/_name/_developmentfoldername");
    ctx.Load(targetFolder);
    ctx.ExecuteQuery();

    // 上传文件逻辑
    string localFilePath = Path.Combine(@"C:\Data\ACH_Files", $"ACH_{DateTime.Now:MM_dd_yyyy}", $"{DateTime.Now:MM_dd_yyyy}_ACH_organization.xlsx");
    FileCreationInformation newFile = new FileCreationInformation();
    newFile.Content = System.IO.File.ReadAllBytes(localFilePath);
    newFile.Url = Path.GetFileName(localFilePath); // 直接取文件名更可靠

    Microsoft.SharePoint.Client.File uploadFile = targetFolder.Files.Add(newFile);
    ctx.Load(uploadFile);
    ctx.ExecuteQuery();

    Console.WriteLine($"文件已上传:{uploadFile.ServerRelativeUrl}");
}

3. 额外注意事项

  • 权限验证:确保使用的账号拥有目标文件夹的写入权限,避免因权限不足导致隐性错误
  • 路径拼接:使用Path.Combine处理本地文件路径,避免手动拼接出现格式错误
  • 异常排查:捕获ClientRequestException时,可读取ServerErrorDetails获取更详细的错误信息,便于定位问题

方案调整建议

如果上述修正后仍有问题,建议改用Microsoft Graph API替代SharePoint CSOM:

  • Graph API是微软推荐的云服务访问接口,对OneDrive/SharePoint的支持更全面
  • 支持应用权限模式(无需用户账号密码),更适合控制台程序这类无人值守场景

内容的提问来源于stack exchange,提问作者FancyDanwithaBand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 16:02:48