如何用C#通过REST API上传文件至SharePoint?遇请求方法错误求参考
先解决Postman测试的错误
错误提示明确指出:The HTTP method 'GET' cannot be used to access the resource 'Add',上传文件到SharePoint REST API需要使用POST方法(对应Add操作)或者PUT方法(直接覆盖上传),你当前使用的GET是只读请求,无法完成写入操作,切换为POST即可继续测试。
C# 调用SharePoint REST API上传文件的示例代码
方法1:POST上传到文档库(Add操作)
using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; class SharePointFileUploader { private static readonly HttpClient _httpClient = new HttpClient(); public static async Task UploadFileToSharePoint(string accessToken, string siteUrl, string libraryName, string localFilePath) { var fileName = Path.GetFileName(localFilePath); // 拼接SharePoint REST API地址 var apiUrl = $"{siteUrl}/_api/web/lists/getbytitle('{libraryName}')/RootFolder/Files/add(url='{fileName}', overwrite=true)"; // 设置请求头,携带access token _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json;odata=verbose")); // 读取本地文件内容 var fileContent = new ByteArrayContent(File.ReadAllBytes(localFilePath)); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream"); // 发送POST请求完成上传 var response = await _httpClient.PostAsync(apiUrl, fileContent); response.EnsureSuccessStatusCode(); // 检查请求是否成功 var result = await response.Content.ReadAsStringAsync(); Console.WriteLine("文件上传成功,返回结果:" + result); } }
方法2:PUT直接上传(支持覆盖或指定子文件夹)
public static async Task UploadFileViaPut(string accessToken, string siteUrl, string libraryName, string localFilePath, string targetFolderPath = "") { var fileName = Path.GetFileName(localFilePath); // 拼接目标文件的API路径,支持子文件夹 var targetUrl = string.IsNullOrEmpty(targetFolderPath) ? $"{siteUrl}/_api/web/GetFolderByServerRelativeUrl('{libraryName}')/Files/add(url='{fileName}', overwrite=true)" : $"{siteUrl}/_api/web/GetFolderByServerRelativeUrl('{libraryName}/{targetFolderPath}')/Files/add(url='{fileName}', overwrite=true)"; _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var fileBytes = File.ReadAllBytes(localFilePath); var request = new HttpRequestMessage(HttpMethod.Put, targetUrl); request.Content = new ByteArrayContent(fileBytes); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); var response = await _httpClient.SendAsync(request); response.EnsureSuccessStatusCode(); Console.WriteLine("文件上传完成"); }
关键注意事项
- 确保
accessToken拥有SharePoint文档库的写入权限(至少Edit级别) - 替换代码中的
siteUrl(示例格式:https://你的租户.sharepoint.com/sites/你的站点)、libraryName(文档库名称,如"文档")、localFilePath为实际值 - 若上传到子文件夹,需确保目标子文件夹已存在,否则会返回路径不存在的错误
- 上传大文件时,建议使用SharePoint的分片上传机制(通过
UploadSession接口实现)
内容的提问来源于stack exchange,提问作者Amruthavarshini M
相关产品推荐
相关产品推荐

