Reputation: 1498
Following example code:
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
}
The fs.files
collection is filled, but the fs.chunks
collection is empty.
Whats wrong with my code? I'm using MongoDB 2.4.7 on Win8 and the official C# driver from NuGet.
Upvotes: 0
Views: 912
Reputation: 600
The problem here is not the mongodb API.
Each write on a (memory)stream will increase its Position to the new end. Now each following read operation on the stream starts at that Position, which pointing to the end of the stream.
You have two options.
Set ms.Position = 0 before you pass the stream to Upload. Or pass the artifactContent to the MemoryStream contructor, which initializes the stream with that data without changing its Position.
Upvotes: 6