|
namespace TestMongo
{
using System;
using System.IO;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.GridFS;
public partial class Program
{
#region Public Methods and Operators
public static void DemoGridFS(MongoDatabase database)
{
var assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
var directoryName = Path.GetDirectoryName(assemblyPath);
string fullyQualifiedUpLoadName = directoryName+@"\Images\mars.png";
//The uploaded file name equals fullyQualifiedUpLoadName
MongoGridFSFileInfo gridFsInfo = database.GridFS.Upload(fullyQualifiedUpLoadName);
//Here the uploaded file is given the name 'mars.png'
using (var fs = new FileStream(fullyQualifiedUpLoadName, FileMode.Open))
{
database.GridFS.Upload(fs, "mars.png");
}
// Add metadata to facilitate searching.
var photoMetadata = new BsonDocument
{ { "Category", "Astronomy" }, { "SubGroup", "Planet" }, { "ImageWidth", 640 }, { "ImageHeight", 480 } };
database.GridFS.SetMetadata(gridFsInfo, photoMetadata);
//Build an index to search the metadata
MongoCollection<BsonDocument> coll = database.GetCollection("fs.files");
IndexKeysBuilder keys = IndexKeys.Ascending("metadata.Category", "metadata.SubGroup");
//Add an optional name- useful for admin
IndexOptionsBuilder options = IndexOptions.SetName("PhotoIndex");
//This locks the database while the index is being built
coll.EnsureIndex(keys, options);
//Search using the PhotoIndex
MongoCursor<MongoGridFSFileInfo> astronomyPics =
database.GridFS.Find(Query.EQ("metadata.Category", "Astronomy"));
//use a filename to download.
string fullyQualifiedDownLoadName = directoryName + @"\Images\mars2.png"; ;
database.GridFS.Download(fullyQualifiedDownLoadName, fullyQualifiedUpLoadName);
MongoCursor<MongoGridFSFileInfo> filesInfo = database.GridFS.FindAll();
if (filesInfo.Any())
{
Console.WriteLine("The following files have been uploaded.");
}
foreach (MongoGridFSFileInfo fileInfo in filesInfo)
{
Console.WriteLine(
"Name {0} size {1} uploaded on {2}",
fileInfo.Name,
fileInfo.Length,
fileInfo.UploadDate.ToShortDateString());
}
// database.GridFS.Delete(fullyQualifiedUpLoadName);
// database.GridFS.Delete("mars.png");
}
#endregion
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.