Skip to content

Instantly share code, notes, and snippets.

@kaushikraj
Last active August 29, 2015 13:56
Show Gist options
  • Save kaushikraj/9177532 to your computer and use it in GitHub Desktop.
Save kaushikraj/9177532 to your computer and use it in GitHub Desktop.
A simple wrapper to GridFS in mongodb for CRUD functionality on files.
/// <summary>
/// Singleton for MongoDB connection (just a sample - for an idea)
/// </summary>
public class ConnectionInformation
{
#region fields
private static ConnectionInformation instance;
private static object syncLock = new object();
#endregion
#region public properties
public static ConnectionInformation Instance
{
get
{
if (instance == null)
{
lock (syncLock)
{
if (instance == null)
{
instance = new ConnectionInformation();
}
}
}
return instance;
}
}
public MongoDatabase Database
{
get
{
return database;
}
}
#endregion
}
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.GridFS;
using System;
using System.IO;
public class MongoFileSystem
{
///<summary>
/// checks if a file exists with the given path.
///</summary>
public bool Exists(string path)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
IMongoQuery query = Query.EQ("filename", path);
MongoGridFSFileInfo file = ConnectionInformation.Instance.Database.GridFS.FindOne(query);
return (file != null);
}
///<summary>
/// returns Stream to the file with given path. returns null
/// if the file does not exist.
///</summary>
public Stream GetFile(string path)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
IMongoQuery query = Query.EQ("filename", path);
MongoGridFSFileInfo file = ConnectionInformation.Instance.Database.GridFS.FindOne(query);
Stream stream = null;
if (file != null)
{
stream = file.OpenRead();
}
return stream;
}
/// <summary>
/// saves a file in the given path. if the file already exists
/// in the path, throws exception.
/// </summary>
public void Save(string path, string filename)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
if (string.IsNullOrEmpty(filename))
{
throw new ArgumentNullException("filename");
}
if (!File.Exists(filename))
{
throw new ArgumentException("filename");
}
MongoGridFSFileInfo gridFsInfo = ConnectionInformation.Instance.Database.GridFS.Upload(filename, path);
}
/// <summary>
/// deletes the file in the given path.
/// </summary>
public void Delete(string path)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
ConnectionInformation.Instance.Database.GridFS.Delete(path);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment