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

WinForms C# .NET8 操作OneDrive文件报错及功能实现求助

解决WinForms .NET8中OneDrive操作的两个错误及功能实现

错误原因及解决方法

1. 找不到DelegateAuthenticationProvider类型

  • 原因:Microsoft Graph SDK v5+已移除该类,旧版(v4及以前)的认证方式已被废弃,改用基于TokenCredential的认证体系。
  • 解决:
    • 安装最新稳定版的NuGet包:Microsoft.Graph和Microsoft.Identity.Client,不要安装已废弃的Microsoft.Graph.Auth。
    • 使用InteractiveBrowserCredential或其他TokenCredential实现来创建GraphServiceClient。

2. DriveRequestBuilder不包含Root定义

  • 原因:要么是NuGet包版本过时/错误,要么是缺少Microsoft.Graph命名空间引用,或者代码路径写法错误。
  • 解决:
    • 确保安装最新版Microsoft.Graph包,清理NuGet缓存后重新安装。
    • 代码中添加using Microsoft.Graph;引用。
    • 个人OneDrive根目录的正确访问路径为_graphClient.Me.Drive.Root;OneDrive for Business需替换为对应站点的Drive路径。

完整功能实现代码

1. 控件准备

在WinForms窗体中添加:

  • DataGridView(命名dataGridView1)
  • 三个按钮:btnLoadFiles(加载列表)、btnDelete(删除)、btnUpload(上传)
  • OpenFileDialog(命名openFileDialog1)

2. 核心代码

using Microsoft.Graph;
using Microsoft.Identity.Client;
using System.Data;
using System.IO;
using System.Windows.Forms;

namespace OneDriveWinFormsDemo
{
    public partial class MainForm : Form
    {
        private GraphServiceClient _graphClient;

        public MainForm()
        {
            InitializeComponent();
        }

        // 初始化Graph客户端
        private async Task InitializeGraphClient()
        {
            var clientId = "你的Azure应用客户端ID";
            var scopes = new[] { "Files.ReadWrite", "User.Read" };

            var options = new InteractiveBrowserCredentialOptions
            {
                ClientId = clientId,
                TenantId = "common", // 个人账号用common,组织账号填租户ID
                RedirectUri = new Uri("http://localhost"), // 需与Azure注册的重定向URI一致
            };

            var credential = new InteractiveBrowserCredential(options);
            _graphClient = new GraphServiceClient(credential, scopes);
        }

        // 加载OneDrive文件/文件夹列表到DataGridView
        private async void btnLoadFiles_Click(object sender, EventArgs e)
        {
            if (_graphClient == null)
            {
                await InitializeGraphClient();
            }

            try
            {
                var items = await _graphClient.Me.Drive.Root.Children.GetAsync(req =>
                {
                    req.QueryParameters.Select = new[] { "id", "name", "size", "file", "folder" };
                });

                var dt = new DataTable();
                dt.Columns.Add("ID", typeof(string));
                dt.Columns.Add("名称", typeof(string));
                dt.Columns.Add("大小", typeof(long));
                dt.Columns.Add("类型", typeof(string));

                foreach (var item in items.Value)
                {
                    var itemType = item.Folder != null ? "文件夹" : "文件";
                    dt.Rows.Add(item.Id, item.Name, item.Size ?? 0, itemType);
                }

                dataGridView1.DataSource = dt;
                dataGridView1.Columns["ID"].Visible = false; // 隐藏ID列
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载失败:{ex.Message}");
            }
        }

        // 删除选中的文件/文件夹
        private async void btnDelete_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选中要删除的项");
                return;
            }

            var selectedItemId = dataGridView1.SelectedRows[0].Cells["ID"].Value.ToString();

            if (_graphClient == null)
            {
                await InitializeGraphClient();
            }

            try
            {
                await _graphClient.Me.Drive.Items[selectedItemId].DeleteAsync();
                MessageBox.Show("删除成功");
                await btnLoadFiles_Click(sender, e); // 刷新列表
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除失败:{ex.Message}");
            }
        }

        // 上传文件到OneDrive根目录
        private async void btnUpload_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            var filePath = openFileDialog1.FileName;
            var fileName = Path.GetFileName(filePath);

            if (_graphClient == null)
            {
                await InitializeGraphClient();
            }

            try
            {
                using var fileStream = new FileStream(filePath, FileMode.Open);
                await _graphClient.Me.Drive.Root.ItemWithPath(fileName).Content.PutAsync(fileStream);
                MessageBox.Show("上传成功");
                await btnLoadFiles_Click(sender, e); // 刷新列表
            }
            catch (Exception ex)
            {
                MessageBox.Show($"上传失败:{ex.Message}");
            }
        }
    }
}

3. Azure应用配置注意事项

  • 在Azure AD中注册桌面/移动应用,添加重定向URI http://localhost。
  • 添加API权限:Files.ReadWrite(委托权限)、User.Read(委托权限),个人账号可直接用户同意,组织账号需管理员同意。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 18:30:19