/// <summary>
        /// Refreshes the GridFS file info from the server.
        /// </summary>
        public void Refresh()
        {
            using (_server.RequestStart(_serverInstance))
            {
                var gridFS          = new MongoGridFS(_server, _databaseName, _settings);
                var database        = gridFS.GetDatabase();
                var filesCollection = gridFS.GetFilesCollection(database);

                MongoCursor <BsonDocument> cursor;
                if (_id != null)
                {
                    cursor = filesCollection.Find(Query.EQ("_id", _id));
                }
                else if (_name != null)
                {
                    cursor = filesCollection.Find(Query.EQ("filename", _name)).SetSortOrder(SortBy.Descending("uploadDate"));
                }
                else
                {
                    throw new InvalidOperationException("Cannot refresh FileInfo when both Id and Name are missing.");
                }
                var fileInfo = cursor.SetLimit(1).FirstOrDefault();
                CacheFileInfo(fileInfo); // fileInfo will be null if file does not exist
            }
        }
        private void UpdateMetadata()
        {
            using (_fileInfo.Server.RequestStart(null, ReadPreference.Primary))
            {
                var gridFS          = new MongoGridFS(_fileInfo.Server, _fileInfo.DatabaseName, _fileInfo.GridFSSettings);
                var database        = gridFS.GetDatabase(ReadPreference.Primary);
                var filesCollection = gridFS.GetFilesCollection(database);

                BsonValue md5 = BsonNull.Value;
                if (_updateMD5)
                {
                    var md5Command = new CommandDocument
                    {
                        { "filemd5", _fileInfo.Id },
                        { "root", gridFS.Settings.Root }
                    };
                    var md5Result = database.RunCommand(md5Command);
                    md5 = md5Result.Response["md5"].AsString;
                }

                var query  = Query.EQ("_id", _fileInfo.Id);
                var update = Update
                             .Set("length", _length)
                             .Set("md5", md5);

                filesCollection.Update(query, update);
            }
        }
 /// <summary>
 /// Moves the most recent version of a GridFS file.
 /// </summary>
 /// <param name="destFileName">The destination file name.</param>
 public void MoveTo(string destFileName)
 {
     EnsureServerInstanceIsPrimary();
     using (_server.RequestStart(_serverInstance))
     {
         var gridFS          = new MongoGridFS(_server, _databaseName, _settings);
         var database        = gridFS.GetDatabase(ReadPreference.Primary);
         var filesCollection = gridFS.GetFilesCollection(database);
         var query           = Query.EQ("_id", _id);
         var update          = Update.Set("filename", destFileName);
         filesCollection.Update(query, update);
     }
 }
        /// <summary>
        /// Deletes a GridFS file.
        /// </summary>
        public void Delete()
        {
            EnsureServerInstanceIsPrimary();
            using (_server.RequestStart(_serverInstance))
            {
                var gridFS = new MongoGridFS(_server, _databaseName, _settings);
                gridFS.EnsureIndexes();

                if (Exists)
                {
                    var database         = gridFS.GetDatabase(ReadPreference.Primary);
                    var filesCollection  = gridFS.GetFilesCollection(database);
                    var chunksCollection = gridFS.GetChunksCollection(database);

                    filesCollection.Remove(Query.EQ("_id", _id), gridFS.Settings.WriteConcern);
                    chunksCollection.Remove(Query.EQ("files_id", _id), gridFS.Settings.WriteConcern);
                }
            }
        }
        private void OpenCreate()
        {
            EnsureServerInstanceIsPrimary();
            using (_fileInfo.Server.RequestStart(null, _fileInfo.ServerInstance))
            {
                var gridFS          = new MongoGridFS(_fileInfo.Server, _fileInfo.DatabaseName, _fileInfo.GridFSSettings);
                var database        = gridFS.GetDatabase(ReadPreference.Primary);
                var filesCollection = gridFS.GetFilesCollection(database);

                gridFS.EnsureIndexes();

                _fileIsDirty = true;
                if (_fileInfo.Id == null)
                {
                    _fileInfo.SetId(ObjectId.GenerateNewId());
                }

                var aliases = (_fileInfo.Aliases != null) ? new BsonArray(_fileInfo.Aliases) : null;
                var file    = new BsonDocument
                {
                    { "_id", _fileInfo.Id },
                    { "filename", _fileInfo.Name, !string.IsNullOrEmpty(_fileInfo.Name) },
                    { "length", 0 },
                    { "chunkSize", _fileInfo.ChunkSize },
                    { "uploadDate", _fileInfo.UploadDate },
                    { "md5", BsonNull.Value },                                                              // will be updated when the file is closed (unless UpdateMD5 is false)
                    { "contentType", _fileInfo.ContentType, !string.IsNullOrEmpty(_fileInfo.ContentType) }, // optional
                    { "aliases", aliases, aliases != null },                                                // optional
                    { "metadata", _fileInfo.Metadata, _fileInfo.Metadata != null } // optional
                };
                filesCollection.Insert(file);

                _length   = 0;
                _position = 0;
            }
        }
        private void UpdateMetadata()
        {
            using (_fileInfo.Server.RequestStart(null, ReadPreference.Primary))
            {
                var gridFS = new MongoGridFS(_fileInfo.Server, _fileInfo.DatabaseName, _fileInfo.GridFSSettings);
                var database = gridFS.GetDatabase(ReadPreference.Primary);
                var filesCollection = gridFS.GetFilesCollection(database);

                BsonValue md5 = BsonNull.Value;
                if (_updateMD5)
                {
                    var md5Command = new CommandDocument
                {
                    { "filemd5", _fileInfo.Id },
                    { "root", gridFS.Settings.Root }
                };
                    var md5Result = database.RunCommand(md5Command);
                    md5 = md5Result.Response["md5"].AsString;
                }

                var query = Query.EQ("_id", _fileInfo.Id);
                var update = Update
                    .Set("length", _length)
                    .Set("md5", md5);

                filesCollection.Update(query, update);
            }
        }
        private void OpenCreate()
        {
            EnsureServerInstanceIsPrimary();
            using (_fileInfo.Server.RequestStart(null, _fileInfo.ServerInstance))
            {
                var gridFS = new MongoGridFS(_fileInfo.Server, _fileInfo.DatabaseName, _fileInfo.GridFSSettings);
                var database = gridFS.GetDatabase(ReadPreference.Primary);
                var filesCollection = gridFS.GetFilesCollection(database);

                gridFS.EnsureIndexes();

                _fileIsDirty = true;
                if (_fileInfo.Id == null)
                {
                    _fileInfo.SetId(ObjectId.GenerateNewId());
                }

                var aliases = (_fileInfo.Aliases != null) ? new BsonArray(_fileInfo.Aliases) : null;
                var file = new BsonDocument
                {
                    { "_id", _fileInfo.Id },
                    { "filename", _fileInfo.Name, !string.IsNullOrEmpty(_fileInfo.Name) },
                    { "length", 0 },
                    { "chunkSize", _fileInfo.ChunkSize },
                    { "uploadDate", _fileInfo.UploadDate },
                    { "md5", BsonNull.Value }, // will be updated when the file is closed (unless UpdateMD5 is false)
                    { "contentType", _fileInfo.ContentType, !string.IsNullOrEmpty(_fileInfo.ContentType) }, // optional
                    { "aliases", aliases, aliases != null }, // optional
                    { "metadata", _fileInfo.Metadata, _fileInfo.Metadata != null } // optional
                };
                filesCollection.Insert(file);

                _length = 0;
                _position = 0;
            }
        }