using( var f = db.GridFS.Create( "test.txt" ) ) { var bytes = System.Text.Encoding.ASCII.GetBytes( "content content content" ); f.Write( bytes, 0, bytes.Length ); } db.GridFS.SetMetadata( db.GridFS.FindOne( "test.txt" ), "metadata metadata metadata" ); var info = db.GridFS.FindOne( "test.txt" );
The above code when run the first time will give an exception at the last line. As:
System.InvalidCastException: Unable to cast object of type 'MongoDB.Bson.BsonString' to type 'MongoDB.Bson.BsonDocument'.
The exception is generated internally by the C# driver when it assumes the 'metadata' field as a BsonDocument despite allowing us to set it to something else only a couple of lines above.
In other words, the C# driver can create a GridFS entry that it can't load.
All GridFS functions on this file entry are wedged. You cannot edit it, you cannot replace, update, or even delete it.
The fatal trigger is SetMetadata, although using another driver to do the same operation is a viable alternative. Ultimately, inside the C# driver the presence of the "metadata" field causes an unstoppable type cast to occur when doing any operation with the tainted file entry - even just trying to delete it is fatal!
For example, the following call now gives the same exception:
db.GridFS.Delete( "test.txt" );
Knowing the file ID does not help, the following also causes the same exception:
db.GridFS.DeleteById( new ObjectId( "5498dfa9f8efe9309c99e9d3" ) );
The offending line of code for v1.9.2 is here:
https://github.com/mongodb/mongo-csharp-driver/blob/v1.9.2/MongoDB.Driver/GridFS/MongoGridFSFileInfo.cs#L759