GridFS.Upload() 不上传流内容

dna*_*dna 0 c# mongodb gridfs mongodb-.net-driver

以下示例代码:

using (var ms = new MemoryStream())
{
    var artifactContent = Encoding.UTF8.GetBytes("content of some file/upload/etc as string");
    ms.Write(artifactContent, 0, artifactContent.Length);

    // ms.Lenght > 0


    var gridFsCreateOptions = new MongoGridFSCreateOptions {ContentType = "text/plain"};
    var gridFsFileInfo = mongoGridFsDatabase.GridFS.Upload(ms, "Test.txt", gridFsCreateOptions);

    // stream is not uploaded and gridFsFileInfo.Lenght == 0
}
Run Code Online (Sandbox Code Playgroud)

fs.files集合被填充,但fs.chunks集合为空。

我的代码有什么问题?我在 Win8 上使用 MongoDB 2.4.7 和来自 NuGet 的官方 C# 驱动程序。

lan*_*win 5

这里的问题不是 mongodb API。

对(内存)流的每次写入都会将其位置增加到新的末尾。现在,流上的每个后续读取操作都从该位置开始,该位置指向流的末尾。

你有两个选择。

在将流传递到 Upload 之前设置 ms.Position = 0。或者将 artifactContent 传递给 MemoryStream 构造函数,该构造函数使用该数据初始化流而不更改其位置。