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

如何将MemoryStream转换为FileStream以传入MS Graph的LargeFileUploadTask?

问题根因与解决方案

优先排查无需转FileStream的解决方法

90%以上的MemoryStream上传耗时异常/超时问题,是传入上传组件前没有重置流的位置导致的,在创建上传任务前加一行代码即可:

fileContents.Position = 0;

如果修复后还是有问题,再按下面的方法转FileStream做对比测试。

正确实现MemoryStream转FileStream

FileStream初始化必须指定文件路径,你可以用系统临时文件目录生成临时文件实现转存:

private static async Task<Boolean> UploadInChunksToSharepoint(MemoryStream fileContents, string fileName)
{
    // 重置MemoryStream指针,必加
    fileContents.Position = 0;
    
    // 生成临时文件路径
    string tempPath = Path.GetTempFileName();
    try
    {
        // 将MemoryStream写入临时文件
        using (var fs = new FileStream(tempPath, FileMode.Truncate, FileAccess.Write))
        {
            fileContents.WriteTo(fs);
        }
        
        // 用临时文件的FileStream执行上传
        using (var uploadStream = new FileStream(tempPath, FileMode.Open, FileAccess.Read))
        {
            // 分片大小建议设置为320KiB的5~10倍,即2.5MB~5MB,分片过大是超时的另一个常见原因
            int maxSliceSize = 320 * 1024 * 8;
            var fileUploadTask = new LargeFileUploadTask<DriveItem>(uploadSession, uploadStream, maxSliceSize);
            // 原有上传逻辑...
        }
    }
    finally
    {
        // 用完删除临时文件,避免占用磁盘空间
        if (File.Exists(tempPath))
        {
            File.Delete(tempPath);
        }
    }
}

其他耗时异常排查点

  • 你原来的分片大小设置320 * 204800 * 4计算结果为250MB,过大的分片在网络波动时极易触发超时,建议调整为2.5MB~10MB区间的320KiB倍数即可。
  • 检查传入的MemoryStream是否被其他逻辑占用,导致流读取被阻塞。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:45:02